版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82192660
Description
当你站在一个迷宫里的时候,往往会被错综复杂的道路弄得失去方向感,如果你能得到迷宫地图,事情就会变得非常简单。
假设你已经得到了一个n*m的迷宫的图纸,请你找出从起点到出口的最短路。
Input
第一行是两个整数n和m(1<=n,m<=100),表示迷宫的行数和列数。
接下来n行,每行一个长为m的字符串,表示整个迷宫的布局。字符'.'表示空地,'#'表示墙,'S'表示起点,'T'表示出口。
Output
输出从起点到出口最少需要走的步数。
Sample Input
3 3
S#T
.#.
...
Sample Output
6
bfs模板题系列
#include <iostream>
#include <queue>
#define SIZE 1500
using namespace std;
struct pos
{
int x, y, step;
};
bool a[SIZE][SIZE];
int b[SIZE][SIZE], dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1}, ex, ey;
pos temppos, cur;
queue<pos> q;
void bfs()
{
int i;
while (!q.empty()) // 基本广搜
{
cur = q.front();
b[cur.x][cur.y] = cur.step;
q.pop();
for (i = 0; i < 4; i++)
{
if (a[cur.x+dx[i]][cur.y+dy[i]])
{
temppos.x = cur.x + dx[i];
temppos.y = cur.y + dy[i];
temppos.step = cur.step + 1;
q.push(temppos);
a[temppos.x][temppos.y] = false;
}
}
}
return;
}
int main(int argc, char** argv)
{
int n, m, i, j, sx, sy;
char c;
cin >> n >> m;
getchar();
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++) // 建图
{
cin >> c;
switch (c)
{
case '.':
a[i][j] = true;
break;
case 'S':
sx = i;
sy = j;
a[i][j] = true;
break;
case 'T':
ex = i;
ey = j;
a[i][j] = true;
break;
}
}
}
temppos.x = sx;
temppos.y = sy;
temppos.step = 0;
q.push(temppos);
bfs();
cout << b[ex][ey] << endl;
return 0;
}