洛谷原题:https://www.luogu.com.cn/problem/P1443
第一次写BFS,不知道为啥会死循环
我的代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int n,m,x,y;
int map[405][405]={-1};
int dx[]={-2,-2,-1,-1,1,1,2,2};
int dy[]={1,-1,2,-2,2,-2,1,-1};
struct node{
int x,y,step;
}now,nextt;
void bfs(int x,int y){
queue<node>q;
map[x][y]=0;
now.x=x;now.y=y;now.step=0;
q.push(now);//初始化
while(!q.empty()){
now=q.front();q.pop();
for(int i=0;i<8;i++){//遍历X个方向
int xx=now.x+dx[i];
int yy=now.y+dy[i];
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&map[xx][yy]==-1) {
nextt.x=xx;nextt.y=yy;nextt.step=now.step+1;
map[xx][yy]=nextt.step;
return;
q.push(nextt);
}
}
}
}
int main(){
cin>>n>>m>>x>>y;
bfs(x,y);
for(int i=1;i<=n;i++)for(int j=1;i<=m;j++)printf("%5d",map[i][j]);
return 0;
}