您的位置:首页 > 其它

poj3984迷宫问题BFS

2018-03-06 23:31 393 查看
迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 28524 Accepted: 16440
Description定义一个二维数组: 
int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。Input一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。Output左上角到右下角的最短路径,格式如样例所示。Sample Input0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0Sample Output(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)题解:bfs+记录路径
#include<iostream>
using namespace std;
int mapp[5][5];
//相邻四个节点
int borderUponX[4] = {0, 0, 1, -1};
int borderUponY[4] = {1, -1, 0, 0};
int frontt = 0, rear = 1;
struct node
{
int pre;
int x;
int y;
} path[100];
void print(int i)
{
if (path[i].pre != -1)
{
print(path[i].pre);
cout << "(" << path[i].x << ", " << path[i].y << ")" << endl;
}
else
cout << "(" << path[i].x << ", " << path[i].y << ")" << endl;
}
void bfs(int x, int y)
{
//开始节点(出发),前面没有节点了
path[frontt].x = x;
path[frontt].y = y;
path[frontt].pre = -1;
//当front == rear的时候说明已经走完了所有“相邻”节点且都不通
while (frontt < rear)
{
for (int i = 0; i != 4; i++)
{
//相邻节点坐标
int pathX = path[frontt].x + borderUponX[i];
int pathY = path[frontt].y + borderUponY[i];
//不符合
4000
的节点(遇到边界或已经走过了)
if (pathY < 0 || pathX < 0 || pathX > 4 || pathY > 4 || mapp[pathX][pathY])
continue;
else
{//将front的相邻的可以过去的并且是还没有走过的节点加到路径里面
mapp[pathX][pathY] = 1;
path[rear].x = pathX;
path[rear].y = pathY;
path[rear].pre = frontt;
rear++;
}
if (pathX == 4 && pathY == 4)
{
print(rear - 1);
break;
}
}
frontt++;
}
}

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