AC代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
using namespace std;
const int N =110;
int mp[N][N];
int sx,sy;
bool vis[N][N];
struct node{
int x,y;
};
int n,m;
int dx[] = {1,-1,0,0};
int dy[] = {0,0,-1,1};
//int cnt;
int path[N][N];
void bfs(int xx,int yy){
queue<node> q;
q.push({xx,yy});
vis[xx][yy] = true;
path[xx][yy] = 0;
while(!q.empty()){
node temp = q.front();
q.pop();
for(int i=0;i<4;i++){
int nx = dx[i] + temp.x;
int ny = dy[i] + temp.y;
if(nx > n || nx < 1 || ny > m || ny < 1) continue;
if(vis[nx][ny]) continue;
if(mp[nx][ny] == 1) continue;
if(!vis[nx][ny] && mp[nx][ny] == 0){
vis[nx][ny] = true;
// cnt++;//这是算能到达的点
path[nx][ny] = path[temp.x][temp.y] + 1;
q.push({nx,ny});
}
if(nx == n && ny == m) {
// printf("%d",cnt);
printf("%d",path[n][m]);
return ;
}
}
}
return ;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
int c;
scanf("%d",&c);
mp[i][j] = c;
}
}
if(n==1 && m==1){
printf("0");
}
else bfs(1,1);
return 0;
}
结果: