正文
增加 18 行删除 18 行
7 行未改动89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354557 行未改动#include<bits/stdc++.h>using namespace std;const int N = 505;char M[N][N];//保存地图bool vis[N][N];//这个点是否走过int dx[4] = {1 , -1 , 0 , 0};int dy[4] = {0 , 0 , 1 , -1};//四个方向int step[N][N];//到每个点需要的最少步数struct node{int x , y;};int n , m;queue<node> q;void bfs(int x , int y){vis[x][y] = 1;q.push({x , y});while(!q.empty()){//注意:函数empty()在空的时候才会返回1int tx = q.front().x;int ty = q.front().y;//别弄反了for(int i = 0;i < 4;i ++){//一次枚举每个方向int nx = tx + dx[i];int ny = ty + dy[i];//向该方向移动后所在位置if(vis[nx][ny] == 0 && nx > 0 && nx <= n && ny > 0 && ny <= m && ((M[tx][ty] == '.' && M[nx][ny] == '#') || (M[tx][ty] == '#' && M[nx][ny] == '.'))){//是否走过这个点/位置是否合法vis[nx][ny] = 1;step[nx][ny] = step[tx][ty] + 1;//步数+1q.push({nx , ny});//加入}}q.pop();//这个点已经枚举了,弹出}}signed main(){cin >> n >> m;for(int i = 1;i <= n;i ++){//输入for(int j = 1;j <= m;j ++){cin >> M[i][j];}}bfs(1 , 1);//从纵1横1开始if(vis[n][m] == 0){//如果没有被遍历到cout << -1;//则没有路径能到达,输出-1return 0;}cout << step[n][m];//输出到达n,m最少步数return 0;}```7 行未改动89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354557 行未改动#include<bits/stdc++.h>using namespace std;const int N = 505;char M[N][N];//保存地图bool vis[N][N];//这个点是否走过int dx[4] = {1 , -1 , 0 , 0};int dy[4] = {0 , 0 , 1 , -1};//四个方向int step[N][N];//到每个点需要的最少步数struct node{int x , y;};int n , m;queue<node> q;void bfs(int x , int y){vis[x][y] = 1;q.push({x , y});while(!q.empty()){//注意:函数empty()在空的时候才会返回1int tx = q.front().x;int ty = q.front().y;//别弄反了for(int i = 0;i < 4;i ++){//一次枚举每个方向int nx = tx + dx[i];int ny = ty + dy[i];//向该方向移动后所在位置if(vis[nx][ny] == 0 && nx > 0 && nx <= n && ny > 0 && ny <= m && ((M[tx][ty] == '.' && M[nx][ny] == '#') || (M[tx][ty] == '#' && M[nx][ny] == '.'))){//是否走过这个点/位置是否合法vis[nx][ny] = 1;step[nx][ny] = step[tx][ty] + 1;//步数+1q.push({nx , ny});//加入}}q.pop();//这个点已经枚举了,弹出}}signed main(){cin >> n >> m;for(int i = 1;i <= n;i ++){//输入for(int j = 1;j <= m;j ++){cin >> M[i][j];}}bfs(1 , 1);//从纵1横1开始if(vis[n][m] == 0){//如果没有被遍历到cout << -1;//则没有路径能到达,输出-1return 0;}cout << step[n][m];//输出到达n,m最少步数return 0;}```