洛谷 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;
}