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