【题目简述】:给定一个大小为n*m的迷宫。迷宫由通道和墙壁组成,每一步可以向邻接的上下左右四格的通道移动。请求出起点到终点所需的最小步数。(注:本题假定从起点一定可以移动到终点)
如图:
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
【分析】:广度优先搜索是由近及远的搜索,所以在这个问题中采用BFS很合适,只要注意访问过的位置不再访问就好。同时本题中应用了一个很重要的方法,pair,这个可以再以后的编程中注意积累其使用方法,当然这个也可以换成是结构体变量。
详细见代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int INF = 100000000;
typedef pair<int ,int> P;
char maze[100][100];
int n,m;
int sx,sy;
int gx,gy;
int d[100][100];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int bfs()
{
queue<P> que;
for(int i = 0;i<n;i++)
{
for(int j = 0;j<m;j++)
{
d[i][j] = INF;
}
}
que.push(P(sx,sy));
d[sx][sy] = 0;
while(que.size())
{
P p = que.front();// 小的p 是 大P 类型的。
que.pop();
if(p.first == gx && p.second == gy)
break;
for(int i = 0;i<4;i++)
{
int nx = p.first + dx[i];
int ny = p.second + dy[i];
if(nx>=0 && nx<=n && ny>=0 && ny<=m && maze[nx][ny] != '#' &&d [nx][ny] == INF)
{
que.push(P(nx,ny));
d[nx][ny] = d[p.first][p.second] + 1;
}
}
}
return d[gx][gy];
}
int main()
{
cin>>n>>m;
for(int i = 0;i<n;i++)
{
for(int j = 0;j<n;j++)
{
cin>>maze[i][j];
if(maze[i][j] == 'G')
{
gx = i;
gy = j;
}
if(maze[i][j] == 'S')
{
sx = i;
sy = j;
}
}
}
int resourt = bfs();
cout<<resourt<<endl;
return 0;
}