一样的迷宫,这次要求不是求有多少条出去的路,而是求最短出去的路,使用bfs就可以知道了。
需要用一个char数组保存迷宫
一个int数组表示距离长度
一个bool数组表示是否访问过(这不是唯一的,还有其它的可能性,可以三合一,如这里的表示方式)
问题描述
给你一个 n 行 m 列的二维迷宫。’S’表示起点,’T’ 表示终点,’#’ 表示墙壁,’.’ 表示平地。你需要从 ‘S’ 出发走到 ‘T’,每次只能上下左右走动,并且不能走出地图的范围以及不能走到墙壁上。请你计算出走到终点需要走的最少步数。
输入格式
第一行输入 n, m 表示迷宫大小。(1≤n,m≤100)
接下来输入 n 行字符串表示迷宫,每个字符串长度为 m。(地图保证有且仅有一个终点,一个起始点)
输出格式
输出走到终点的最少步数,如果不能走到终点输出 -1,占一行。
样例输入
3 3
S.#
.#.
.#T
样例输出
-1
#include <iostream>
#include <memory.h>
#include <queue>
using namespace std;
char mazee[110][110];
bool marked[110][110];
int length[110][110];
int step = 0;
int n, m, flag = 0, ex, ey, sx, sy;
struct point {
int x, y;
point(int xx, int yy){
x = xx;
y = yy;
}
};
int xxx[4] = {1, 0, -1, 0};
int yyy[4] = {0, 1, 0, -1};
void bfs(int sx, int sy){
queue<point> qq;
qq.push(point(sx, sy));
length[sx][sy] = 0;
marked[sx][sy] = true;
while (!qq.empty()) {
point temp = qq.front();
qq.pop();
for (int i = 0; i < 4; i++) {
int tx = temp.x + xxx[i];
int ty = temp.y + yyy[i];
if (tx >= 0 && ty >= 0 && tx < n && ty < m && !marked[tx][ty] && mazee[tx][ty] != '#') {
marked[tx][ty] = true;
length[tx][ty] = length[temp.x][temp.y] + 1;
if (tx == ex && ty == ey) {
return;
}
qq.push(point(temp.x + xxx[i], temp.y + yyy[i]));
}
}
}
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
char c = getchar();
while (c == '\n') {
c = getchar();
}
mazee[i][j] = c;
if (mazee[i][j] == 'T') {
ex = i;
ey = j;
}
if (mazee[i][j] == 'S') {
sx = i;
sy = j;
}
}
}
bfs(sx, sy);
if (marked[ex][ey]) {
cout << length[ex][ey];
}else{
cout << -1;
}
return 0;
}