您的位置:首页 > 其它

BFS | 3984 | 迷宫问题

2013-05-13 20:56 676 查看
学习BFS,找到raphealguo的博客介绍BFS,完成了这题。

POJ 3984 迷宫问题

#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;

int map[5][5], visit[25], path[25];                   //
int dir[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; // 左下上右搜索

bool is_leagal(int x, int y)
{
if (x < 0 || x > 4 || y < 0 || y > 4)
return false;
if (map[x][y] == 1)
return false;
return true;
}

void print(int final)
{
if (path[final] != -1)
print(path[final]);
printf("(%d, %d)\n", final / 5, final % 5);
}

void dfs()
{
queue<int> Q;
int now, next;
int x, y, temp_x, temp_y;

// 第一个节点入列
visit[0] = true;
path[0] = -1;
Q.push(0);
while (!Q.empty())
{
// 取出第一个节点
now = Q.front();
Q.pop();
x = now / 5;
y = now % 5;
for (int i = 0; i < 5; ++i)
{
temp_x = x + dir[i][0];
temp_y = y + dir[i][1];
next = temp_x * 5 + temp_y;
if (is_leagal(temp_x, temp_y) && !visit[next])
{
path[next] = now;
if (next == 24) return;
visit[next] = true;
Q.push(next); // 把周围合法节点入列
}
}
}
}

int main()
{
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
scanf("%d", &map[i][j]);
dfs();
print(24);
}
可以最快的获得路径,因为BFS类似一层一层的扒皮,所以可以最快的找到一条路径。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BFS 搜索