宽度优先搜索(BFS)的应用——走迷宫
来源:互联网 发布:龙族js挂机脚本 编辑:程序博客网 时间:2024/06/16 18:17
- 题目描述:
sun所在学校每年都要举行电脑节,今年电脑节有一个新的趣味比赛项目叫做闯迷宫。
sun的室友在帮电脑节设计迷宫,所以室友就请sun帮忙计算下走出迷宫的最少步数。
知道了最少步数就可以辅助控制比赛难度以及去掉一些没有路径到达终点的map。
比赛规则是:从原点(0,0)开始走到终点(n-1,n-1),只能上下左右4个方向走,只能在给定的矩阵里走。
- 输入:
输入有多组数据。
每组数据输入n(0<n<=100),然后输入n*n的01矩阵,0代表该格子没有障碍,为1表示有障碍物。
注意:如果输入中的原点和终点为1则这个迷宫是不可达的。
- 输出:
对每组输入输出该迷宫的最短步数,若不能到达则输出-1。
- 样例输入:
20 10 050 0 0 0 01 0 1 0 10 0 0 0 00 1 1 1 01 0 1 0 0
- 样例输出:
2
8
图的宽度优先搜索BFS
用队列实现
//从顶点v开始的宽度优先搜索
初始化v标记为已到达顶点;
初始化队列q,其中仅包含一个元素;
while(q不空){
从队列中删除顶点w;
令u为邻接于w的顶点;
while(u){
if(u尚未被标记){
把u加入队列
把u标记为已访问的顶点;}
u = 邻接于w的下一个顶点
}
}
#include <iostream>#include <queue>using namespace std;struct Node{//顶点的结构体int x;int y;int step;Node(int x1, int y1, int step1) : x(x1), y(y1), step(step1){ }};int rBFS(int, int **, int ** , const int[][2]);int main(){int n;cin >> n;int **a;//邻接矩阵a = new int*[n];for (int i = 0; i < n; ++i)a[i] = new int[n];for (int i = 0; i < n; ++i){for (int j = 0; j < n; ++j)cin >> a[i][j];}const int direction[][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };//访问的四个方向分别为上下左右int **visit;visit = new int*[n];for (int i = 0; i < n; i++)visit[i] = new int[n];for (int i = 0; i < n; ++i)for (int j = 0; j < n; ++j)visit[i][j] = 0;int result = rBFS(n, a, visit, direction);for (int i = 0; i < n; ++i){delete[]a[i];delete[]visit[i];}delete[] a;delete[] visit;cout << result << endl;system("pause");return result;}int rBFS(int n, int **a, int **visit, const int direction[][2]){Node node(0, 0, 0);queue<Node> q;while (!q.empty()) q.pop();q.push(node);while (!q.empty()){node = q.front();q.pop();if (node.x == n - 1 && node.y == n - 1) return node.step;visit[node.x][node.y] = 1;for (int i = 0; i < 4; ++i){int x = node.x + direction[i][0];int y = node.y + direction[i][1];if (x >= 0 && y >= 0 && x < n && y < n && visit[x][y] == 0 && a[x][y] == 0){visit[x][y] = 1;Node next(x, y, node.step + 1);q.push(next);}}}return -1;}
0 0
- 宽度优先搜索(BFS)的应用——走迷宫
- bfs走迷宫宽度优先搜索
- 走迷宫——深度优先搜索
- hud 1010 走迷宫 搜索—bfs
- 宽度优先搜索——迷宫的最短路径
- BFS 宽度优先搜索——初学
- 深度优先搜索应用:走迷宫
- BFS的应用-走迷宫
- BFS-宽度优先搜索(Breadth First Search)—1
- 宽度优先搜索(BFS)
- BFS(宽度优先搜索)
- 宽度优先搜索(BFS)
- 走迷宫--图的搜索(bfs)并记录路径
- 走迷宫2(广度优先搜索)
- 宽度优先搜索 BFS
- 宽度优先搜索BFS
- 宽度优先搜索bfs
- 广度优先搜索BFS(迷宫问题)
- 3.8
- JAVA 整型和字符串互相转换
- 读好书的心得体会
- 人民日报任仲平:凝聚当代中国的价值公约数
- 第三章第七题(3)
- 宽度优先搜索(BFS)的应用——走迷宫
- <3> unity3d 分包与上google play 之测试(重要)
- 3-5
- mac下profile文件(转载)
- c++第三章作业
- OC语法--单例设计模式,及两种创建方法
- 根目录下各个文件夹的介绍
- 欧拉图算法
- hdu A Simple Game(1851)