给定一个大小为N*M的迷宫,由通道('.')和墙壁('#')组成,其中通道S表示起点,通道G表示终点,每一步移动可以达到上下左右中不是墙壁的位置。试求出起点到终点的最小步数。(本题假定迷宫是有解的)(N,M<=100)
样例输入:
10 10
样例输出:
22
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 200,inf = maxn*maxn;
int n,m;
int D[maxn][maxn];
char Map[maxn][maxn];
typedef pair<int,int> P;
int dx[4] = {-1,0,0,1},dy[4] = {-1,-1,1,1};
int BFS(int x,int y){
queue<P>q;
q.push(P(x,y));
while(!q.empty()){
P next = q.front();
q.pop();
for(int i=0;i<4;i++){
int nx = next.first + dx[i];
int ny = next.second + dy[i];
if(0<=nx && nx<n && 0<=ny && ny<n && Map[nx][ny] == '.' && D[nx][ny] != inf ){
q.push(P(nx,ny));
D[nx][ny] = D[next.first][next.second] + 1;
}
if(Map[nx][ny] == 'G') return D[next.first][next.second] + 1;
}
}
}
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){
scanf("%s",&Map[i]);
}
P S;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
D[i][j] = inf;
if(Map[i][j] == 'S'){
P S(1, 2);
D[i][j] = 0;
}
}
}
printf("%d\n", BFS(S.first,S.second));
return 0;
}