#include<bits/stdc++.h>
using namespace std;
int n,A,B,C,D,vis[350][350]={0},m,mp[350][350],vis2[350][350]={0},sum=1;
int dr[4] = {0,-1,1,0};
int dc[4] = {-1,0,0,1};
int bfs();
struct point{
int row;
int col;
}st,ed;
int main(){
cin>>n>>m;
st.row=0;
st.col=0;
//ed
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>mp[i][j];
}
}
cout<<bfs()<<endl;;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cout<<vis2[i][j]<<" ";
}
cout<<endl;
}
return 1;
}
int bfs(){
//初始化
vis2[0][0]=1;
queue<point> q;
memset(vis,-1,sizeof vis);
q.push(st);
vis[st.row][st.col]=0;
int ans=-1;
//搜索
while(q.size()){
point pt=q.front();
q.pop();
//判断是否停止
if(pt.row==n-1 and pt.col==m-1){
ans=vis[pt.row][pt.col];
break;
}
//继续循环搜索
for(int i=0;i<=3;i++){
int x=pt.row+dr[i];
int y=pt.col+dc[i];
if(0<=x and x<n and 0<=y and y<m and vis[x][y]==-1 and !mp[x][y]){
sum++;
vis2[x][y]=sum;
cout<<x<<" "<<y<<endl;
vis[x][y]=vis[pt.row][pt.col]+1;
q.push((point){x,y});
}
}
}
//返回
return ans;
}
这就是我代码,帮看一下为什么遍历顺序不对,谢谢!