- 给定一个大小为N x M的迷宫。迷宫由通道和墙壁组成,每一步可以由邻接的上下左右四格的通道移动。请求出从起点到终点所需最小步数。
(’#’、’.’、‘S’、'G’分别表示墙壁、通道、起点、终点)
输入:
10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
输出:
22
#include <iostream>
#include <queue>
using namespace std;
int n, m;
int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
char s[105][105];
int dis[105][105];
struct node{
int x, y;
node(int _x, int _y)
{
x = _x;
y = _y;
}
};
int bfs(int x, int y)
{
queue<node> q;
q.push(node(x, y));
dis[x][y] = 0;
while (!q.empty())
{
node now = q.front();
q.pop();
if (s[now.x][now.y] == 'G')
{
return dis[now.x][now.y];
}
for (int i = 0; i < 4; i++)
{
int tx = now.x + dir[i][0], ty = now.y + dir[i][1];
if (tx < 0 || tx >= n || ty < 0 || ty >= m || s[tx][ty] == '#' || dis[tx][ty] != 0x3f3f3f3f)
{
continue;
}
dis[tx][ty] = dis[now.x][now.y] + 1;
q.push(node(tx, ty));
}
}
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
scanf("%s", s[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
dis[i][j] = 0x3f3f3f3f;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (s[i][j] == 'S')
{
cout << bfs(i, j) << endl;
break;
}
}
}
return 0;
}