您的位置:首页 > 其它

宽度优先搜索迷宫问题

2018-02-08 21:06 197 查看
#include <iostream>
#include <queue>
#define MAX_N 100
#define MAX_M 101
using namespace std;
const int INF = 100000000;

//使用pair表示状态时,使用typedef会更加方便一点。
typedef pair<int, int> P;
//输入

char maze[MAX_N][MAX_M + 1];//表示迷宫字符串数的数组。
int N, M;
int sx, sy;//起点坐标
int gx, gy;//终点坐标
int d[MAX_N][MAX_M];//到各个位置的最短距离的数组

//4个方向移动的向量
int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };

//求从(sx,sy)到(gx,gy)的最短距离
//如果无法到达,则是INF
int bfs() {
queue<P>que;
//把所有的位置都初始化为INF
for (int i = 1; i<=N; i++)
for (int j = 1; j<=M; j++) d[i][j] = INF;
//将起点加入到队列,并将这一点位置设置为0
que.push(P(sx, sy));
d[sx][sy] = 0;
//不断循环直到队列的长度为0
while (que.size()) {
//从队列最前端取出元素
P p = que.front(); que.pop();
//如果取出的状态是最后一个即终点,则结束搜索
if (p.first == gx&&p.second == gy)break;
//四个方向的循环
for (int i = 0; i<4; i++) {
//移动之后的位置记为(nx,ny)
int nx = p.first + dx[i], ny = p.second + dy[i];
//判断是否可以移动,且是否已经访问过(d[nx][ny]!=INF就是已经访问过)
if (0 < nx && nx<=N && 0 < ny && ny<=M && maze[nx][ny] != '#'&&d[nx][ny] == INF) {
//可以移动的话,则加入到队列,且该位置的距离确定为到p的距离+1
que.push(P(nx, ny));
d[nx][ny] = d[p.first][p.second] + 1;
}
}
}

return d[gx][gy];
}
int main() {
cin >> N >> M;
cin >> sx >> sy;
cin >> gx >> gy;
for (int i = 1; i<=N; i++) {
for (int j = 1; j<=M; j++) {
cin >> maze[i][j];
}
}
int res = bfs();
cout << res << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: