您的位置:首页 > 其它

BFS 迷宫的最短路径问题

2015-03-30 22:07 369 查看
给点一个N*M的迷宫,再给定起点(sx,sy)和终点(gx,gy),求最短路径的长度(假设存在)。

直接BFS搜索即可。

#include<iostream>
#include<queue>
#define INF 9999999
using namespace std;
int N, M;
char maze[101][101];
typedef pair<int, int>pos;
int sx, sy, gx, gy;
int d[101][101];
//向四个方向转移时的坐标偏移数组
int dx[4] = { -1, 0, 0, 1 };
int dy[4] = { 0, -1, 1, 0 };
int BFS(){
queue<pos> que;
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
d[i][j] = INF;
}
}
que.push(pos(sx,sy));
//loop till the queue is empty
while (!que.empty()){
pos p = que.front();
que.pop();
if (p.first == gx&&p.second == gy){
//end the loop while,as the road reach the end of aim
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(pos(nx, ny));
d[nx][ny] = d[p.first][p.second] + 1;
}
}
}
return d[gx][gy];
}
int main()
{
while (cin >> N >> M){
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
cin >> maze[i][j];
}
}
cout << BFS() << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: