洛谷1443 马的遍历【bfs】

时间:2023-03-09 00:42:01
洛谷1443 马的遍历【bfs】

题目链接:https://www.luogu.org/problemnew/show/P1443

题意:

给一个n*m的棋盘,马在上面走(规则就是象棋中的规则,详细见代码dx,dy数组定义)

问棋盘上每个点马都需要走几步到达。

思路:

简单bfs。注意输出应该用%-5d(不加空格)

 #include<stdio.h>
#include<stdlib.h>
#include<map>
#include<set>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue> using namespace std; int n, m;
struct node{
int x, y;
int step;
}st;
int mat[][]; int dx[] = {, , , -, , -, -, -};
int dy[] = {, -, , , -, -, , -}; bool check(int i, int j)
{
return (i > && i <= n && j > && j <= m);
} int main()
{
scanf("%d%d", &n, &m);
scanf("%d%d", &st.x, &st.y);
memset(mat, -, sizeof(mat));
st.step = ;
queue<node>que;
que.push(st);
mat[st.x][st.y] = ;
while(!que.empty()){
node now = que.front();que.pop();
node tmp;
tmp.step = now.step + ;
for(int i = ; i < ; i++){
tmp.x = now.x + dx[i];
tmp.y = now.y + dy[i];
if(check(tmp.x, tmp.y) && mat[tmp.x][tmp.y] == -){
mat[tmp.x][tmp.y] = tmp.step;
que.push(tmp);
}
}
}
for(int i = ; i <= n; i++){
for(int j = ; j <= m; j++){
printf("%-5d", mat[i][j]);
}
printf("\n");
} return ;
}