洛谷. P1443 马的遍历

洛谷 P1443 马的遍历

题目描述

有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入输出格式
输入格式:

一行四个数据,棋盘的大小和马的坐标

输出格式:

一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)

输入输出样例

输入样例#1:
3 3 1 1

输出样例#1:
0 3 2
3 -1 1
2 1 4

#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
using namespace std;
int vis[410][410],i,j;
int stmp[410][410];
int dir[8][2] = { 1, 2, 1, -2, 2, 1, 2, -1, -1, 2, -1, -2, -2, -1, -2, 1 };
int a,b,c,d;
struct node{
	int x, y;
};
bool checkedge(int x, int y){
	if (x<1 || x>a || y<1 || y>b || vis[x][y]==1)
		return 1;
	return 0;
}
void bfs(int c, int d){
	memset(stmp, -1, sizeof(stmp));
	node now, next;
	queue<node>q;
	now.x = c;
	now.y = d;
	q.push(now);
	stmp[c][d] = 0;
	vis[c][d] = 1;
	while (!q.empty()){
		now = q.front();
		q.pop();
		int nx, ny;
		for ( i = 0; i < 8; i++){
			nx = now.x + dir[i][0];
			ny = now.y + dir[i][1];
			if (checkedge(nx, ny))
				continue;
			next.x = nx;
			next.y = ny;
			stmp[nx][ny] = stmp[now.x][now.y] + 1;
			q.push(next);
			vis[nx][ny] = 1;
		}
	}
	for (i = 1; i <= a; i++, cout << endl)
		for (j = 1; j <= b; j++)
			printf("%-5d", stmp[i][j]);
	return;
}
int main(){
	cin >> a >> b >> c >> d;
	memset(vis, 0, sizeof(vis));
	bfs(c, d);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值