这道题我跟着书上做的,为什么错了
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
int next[15][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
struct coord{ //结构体存储x,y
int x,y;
};
queue<coord>Q; //队列
int ans[310][310];
int main(){
int n,m,sx,sy;
memset(ans,-1,sizeof(ans)); //没访问过的点标记为-1
cin>>n>>m>>sx>>sy;
coord tmp={sx,sy};
Q.push(tmp); //起点入队
ans[sx][sy]=0;
while(!Q.empty()){
coord u=Q.front(); //取出队首
int ux=u.x,uy=u.y; //(ux,uy)记录原点
Q.pop(); //队尾出队
for(int k=0;k<8;k++){
int d=ans[ux][uy]; //d记录上一个位置的步数
int xx=ux+next[k][0],yy=uy+next[k][1]; //(xx,yy)记录现在位置
if(xx<1||xx>n||yy<1||yy>m||ans[xx][yy]||ans[xx][yy]!=-1)
continue;
ans[xx][yy]=d+1; //记录答案=上一个点+1
coord tmp={xx,yy};
Q.push(tmp); //入队
}
}
for(int i=1;i<=n;i++,puts(""))
for(int j=1;j<=m;j++)
printf("%-5d",ans[i][j]);
return 0;
}