Files
ClassFeedback/C++代码/学习/走迷宫.cpp

56 lines
874 B
C++

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int n, m;
const int MAX = 50;
char mapp[MAX][MAX];
int step[MAX][MAX];
struct Node{
int x, y;
};
queue<Node> q;
int fx[] = {0, 0, 1, 0, -1};
int fy[] = {0, 1, 0, -1, 0};
void bfs(int x, int y){
Node dian;
dian.x = x;
dian.y = y;
step[x][y] = 1;
q.push(dian);
while(q.size()){
int cx = q.front().x;
int cy = q.front().y;
int tx, ty;
for(int i = 1; i <= 4; i++){
tx = cx + fx[i];
ty = cy + fy[i];
if(tx >= 1 && tx <= n && ty >= 1 && ty <= m && mapp[tx][ty] == '.' && step[tx][ty] == 0){
q.push({tx, ty});
step[tx][ty] = step[cx][cy] + 1;
if(tx == n && ty == m) return ;
}
}
q.pop();
}
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> mapp[i][j];
}
}
bfs(1, 1);
cout << step[n][m];
return 0;
}