bfs走迷宫
C++#include <bits/stdc++.h>
using namespace std;
struct node{
int x,y,step;
}s;
int n,m,x,y;
int dir[4][2] = {0,1,0,-1,1,0,-1,0};
int vis[1000][1000];
char maps[1000][1000];
int bfs(){
s.x = x;
s.y = y;
s.step = 0;
vis[x][y] = 1;
queue<node> que;
que.push(s);
while(!que.empty()){
node now = que.front();
que.pop();
for(int i = 0;i < 4;i++){
node next = now;
next.x += dir[i][0];
next.y += dir[i][1];
next.step++;
if(next.x <= 0 || next.x > n || next.y <= 0 || next.y > m || maps[next.x][next.y] == '#' || vis[next.x][next.y])
continue;
if(maps[next.x][next.y] == 'E')
return next.step;
vis[next.x][next.y] = 1;
que.push(next);
}
}
return -1;
}
int main(){
memset(maps,'#',sizeof(maps));
cin >> n >> m;
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
cin >> maps[i][j];
if(maps[i][j] == 'S')
x = i,y = j;
}
}
cout << bfs();
return 0;
}