您的位置:首页 > 其它

宽度优先搜索(记录路径)

2017-04-12 11:06 197 查看
迷宫问题 + 记录路径 + 结构体数组(模拟队列,因为我用不好指针记录前驱节点)

从终点向始点宽搜(其实这一题是深搜,无所谓啦)。每拓展一层,这一层的节点各自保存它是由哪个节点拓展来的。

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 Input
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

Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
/*------default---------*/
const int maxn = 1e1 + 7;
int pic[maxn][maxn];
int n = 5;
struct Node {
int x, y, pre;
}q[maxn];
int dir[4][2] = { { 0, -1 },{ 0, 1 },{ -1, 0 },{ 1, 0 } };
void BFS() {
int front = 0, rear = 1;
q[front] = { n - 1, n - 1, -1 };
while (front < rear) {
if (q[front].x == 0 && q[front].y == 0) {
while (q[front].pre != -1) {
cout << "(" << q[front].x << ", " << q[front].y << ")" << endl;
front = q[front].pre;
}
cout << "(" << n - 1 << ", " << n - 1 << ")" << endl;
break;
}
for (int i = 0; i < 4; ++i) {
int x = q[front].x + dir[i][0];
int y = q[front].y + dir[i][1];
if (0 <= x && x < n && 0 <= y && y < n && pic[x][y] == 0) {
pic[x][y] = 1;
q[rear++] = { x, y, front };
}
}
front++;
}
}
int main()
{
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
cin >> pic[i][j];
BFS();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: