1. 问题描述:
给定一个n * m大小的迷宫,其中*代表不可通过的墙壁,而.代表平地,S表示起点,T表示终点,移动过程中,如果当前位置是(x,y)(下标从0开始),而且每次只能前往上下左右(x,y + 1)(x,y - 1)(x - 1,y)(x + 1,y)四个位置的平地,求从起点S到达终点T的最少步数
.....
.*.*.
.*S*.
.***.
...T*
2. 思路分析:
① 因为求解的最少步数,而且我们知道广度优先搜索可以用来求解最少步数的,所以我们可以使用广度优先来进行求解
② 从起点开始进行四个方向的广度优先搜索,最小到达终点的那么步数一定是最少的,所以在循环中我们每弹出一个节点那么进行坐标的判断,看一下是否等于了终点坐标,假如是的话那么直接返回弹出节点的记录的步数即可
③ 这道题目与之前使用广度优先检测联通块的题目是类似的,只是在前面的基础上增加一些代码即可解决
测试数据如下:
5 5
.....
.*.*.
.*S*.
.***.
...T*
2 2 4 3
输出结果是11
3. 下面是具体的代码:
#include<cstdio>
#include<queue>
#include<iostream>
using namespace std;
const int maxn = 100;
struct node{
int x;
int y;
int step;
}S, T, Node;//S为起点,T为终点,Node为临时节点
int n, m;
char maze[maxn][maxn]; //迷宫信息
bool inq[maxn][maxn] = {false};//记录是否入过队列
int posx[4] = {0, 0, 1, -1};
int posy[4] = {1, -1, 0, 0};
bool test(int x, int y){
if(x >= n || x < 0 || y >= m || y < 0) return false;
if(maze[x][y] == '*') return false;
if(inq[x][y] == true) return false;
return true;
}
int bfs(){
queue<node> que;
que.push(S);
while(!que.empty()){
node top = que.front();
que.pop();
if(top.x == T.x && top.y == T.y){
return top.step;
}
for(int i = 0; i < 4; i++){
int newx = top.x + posx[i];
int newy = top.y + posy[i];
if(test(newx, newy)){
Node.x = newx;
Node.y = newy;
Node.step = top.step + 1;
que.push(Node);
inq[newx][newy] = true;
}
}
}
}
int main(void){
scanf("%d%d", &n, &m);
for(int i = 0; i < n; ++i){
getchar();
for(int j = 0; j < m; ++j){
maze[i][j] = getchar();
}
maze[i][m + 1] = '\0';
}
scanf("%d%d%d%d", &S.x, &S.y, &T.x, &T.y);
printf("%d", bfs());
return 0;
}