宽度遍历
宽度优先搜索(BFS,Breadth-First Search)也是搜索的手段之一。它与深度优先搜索类似,从某个状态除法探索所有可以到达的状态。
与深度优先搜索的不同之处在于搜索的顺序,宽度优先搜索总是先搜索距离初始状态近的状态。也就是说,它是按照开始状态->只需1次转移就可以到达的所有状态->只需2次转移就可以到达的所有状态->……这样的顺序进行搜索。对于同一个状态,宽度优先搜索只经过一次,因此复杂度为O(状态数x转移的方式)。
题一、迷宫的最短路径问题
给定一个大小为NxM的迷宫。迷宫由通道和墙壁组成,每一步可以向邻接的上下左右四格的通道移动。请求出从起点到终点所需的最小步数。请注意,本题假定从起点一定可以移动到终点。
限制条件:N,M <= 100
样例输入:
N=10, M=10(迷宫如下图所示。 '#', '.', 'S', 'G'分别表示墙壁、通道、起点和终点)
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
样例输出:22
/*
10 10
# S # # # # # # . #
. . . . . . # . . #
. # . # # . # # . #
. # . . . . . . . .
# # . # # . # # # #
. . . . # . . . . #
. # # # # # # # . #
. . . . # . . . . .
. # # # # . # # # .
. . . . # . . . G #
*/
#include <iostream>
#include<queue>
using namespace std;
const int INF=100000;
int n,m,sx,sy,ex,ey;//sx,sy是起点坐标,ex,ey是终点坐标
int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};//表示左右位移的大小
int step[105][105];//点到各个位置的最小路途的数组
char maze[105][105];//表示迷宫的大小
typedef pair<int,int> P;//点的状态符
void solve();
int bfs();
int main()
{
while(cin>>n>>m){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>maze[i][j];
if(maze[i][j]=='S'){
sx=i;sy=j;
}
if(maze[i][j]=='G'){
ex=i;ey=j;
}
step[i][j]=INF;//把所有的位置初始化成INF
}
}
solve();
}
return 0;
}
void solve(){
int ans=bfs();
cout<<ans<<endl;
}
int bfs(){
queue<P> q;
q.push(P(sx,sy));//输入起点
step[sx][sy]=0;//表示最短距离的数组
while(q.size()){
P p=q.front();//p等于队首元素,是一个二维数组
if(p.first==ex&&p.second==ey) break;//如果取出的状态是终点,则结束搜索
q.pop();//弹出
for(int i=0;i<4;i++){//前后左右循环一遍
int tx=p.first+dx[i],ty=p.second+dy[i];
//判断是否可以移动且是否访问过(step[tx][ty] != INF即已经访问过)
if(tx>=0&&tx<n&&ty>=0&&ty<m&&step[tx][ty]==INF&&maze[tx][ty]!='#'){
q.push(P(tx,ty));
step[tx][ty]=step[p.first][p.second]+1;//到该位置的距离确定是到p的距离加1
}
}
}
return step[ex][ey];
}