给定一个大小为N×M的迷宫。迷宫由通道和墙壁组成,每一步可以向邻接的上下左右四个的通道移动。请求出从起点到终点所需的最小步数。请注意,本题假定从起点一定可以移动到终点。
限制条件:
N,M <= 100
样例:
输入:
N=10 M=10 ('#', '.' , 'S', 'G'分别表示墙壁、通道、起点和终点)
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
输出:
22
思路:bfs从初始状态呈扩散型分为多条支路,最先到达终点的就是最短路径
1.用一个结构存储该位置上的状态
2.设置一个bool数组,将走过的位置进行标记
#include<iostream>
#include<queue>
using namespace std;
const int INF = 1e8;
const int MAX_N = 110;
typedef struct node{
int x,y,cnt;
}P;
char maze[MAX_N][MAX_N];
bool vis[MAX_N][MAX_N];
int N, M;
int sx,sy,gx,gy;//起点和终点坐标
int dd[4][2] = {{-1,0}, {1,0}, {0,-1}, {0,1}}; //4个方向移动的向量
int bfs(){
queue<P> que;
P p = {sx,sy,0};
vis[sx][sy] = true;
que.push(p);
while(!que.empty()){
p = que.front();
que.pop();
if(p.x == gx && p.y == gy){
return p.cnt;
}
for(int i = 0; i < 4; i++){
int nx = p.x + dd[i][0];
int ny = p.y + dd[i][1];
//判断是否可以移动以及是否已经访问过
if(nx >= 0 && nx < N && ny >= 0 && ny < M && maze[nx][ny] != '#' && !vis[nx][ny]){
P tmp = {nx,ny,p.cnt+1};
que.push(tmp);
vis[nx][ny] = true;
}
}
}
return -1;//无法到达终点
}
int main(){
cin >> N >> M;
cin >> sx >> sy;
cin >> gx >> gy;
for(int i = 0;i < N;i++){
cin >> maze[i];
}
cout << bfs();
return 0;
}