(BFS)广度优先搜索例子:迷宫,寻找连块数
来源:互联网 发布:人工智能有关英语作文 编辑:程序博客网 时间:2024/06/13 21:45
//广度优先搜索
主要分成以下几块
0、节点node结构体;
1、matrix[][],原始矩阵
2、增量数组X[],Y[] 实现该坐标的左右上下的更新坐标
3、判断时候下一个元素需要入队列的函数
4、记录元素坐标时候已经访问的inq[][];
//广度优先 BFS//寻找代码块的个数struct Node_B{ int x, y;};Node_B node;int n, m;const int maxn = 100;int matrix[maxn][maxn];bool inq[maxn][maxn] = { false };int X[4] = { 0, 0, 1, -1 };int Y[4] = { 1, -1, 0, 0 };//判断改点是在矩阵的内部bool judge(int x, int y){ if (x >= n || y>= m ||x<0 || y<0){ return false; } if (matrix[x][y] == 0 || inq[x][y] == true){ return false; } return true;}//广度优先分成的几个步骤需要你充分熟悉 4步骤void BFS(int x, int y){ queue<Node_B> Q; node.x = x; node.y = y; Q.push(node); inq[x][y] = true; while (!Q.empty()) { Node_B top = Q.front();//取出队列头,可以后的当前的坐标值便于更新下一次的坐标 Q.pop(); for (int i = 0; i < 4; i++) { int newX = top.x + X[i]; int newY = top.y+Y[i]; if (judge(newX, newY)){ node.x = newX; node.y = newY; Q.push(node); inq[newX][newY] = true; } } }}void testBFS(){ cin >> n >> m; for (int x = 0; x < n; x++) { for (int y = 0; y < m; y++) { cin >> matrix[x][y]; } } int ans = 0;//记录存放的快速 for (int x = 0; x < n; x++) { for (int y = 0; y < m; y++) { if (matrix[x][y] ==1 && inq[x][y] ==false) { ans++; BFS(x, y); } } } cout << ans;}
//广度优先搜索的示例二:走迷宫
1.top实际上是每个分支的起点;
2.检索遇到满足maze和inq的田间的就加入队列中去;
// 广度优先2 BFS//迷宫struct Node_C{ int x, y; int step=0;};Node_C node0,S,T;char maze[maxn][maxn];//判断改点是在矩阵的内部bool judge1(int x, int y){ if (x >= n || y >= m || x<0 || y<0){ return false; } if (maze[x][y] == '*' || inq[x][y] == true){ return false; } return true;}//广度优先分成的几个步骤需要你充分熟悉 4步骤int BFS2(){ queue<Node_C> Q; Q.push(S); while (!Q.empty()) { Node_C top = Q.front();//取出队列头,可以后的当前的坐标值便于更新下一次的坐标 Q.pop(); //若全部弹出之后则就返回步数; if (top.x==T.x && top.y==T.y) { return top.step; } for (int i = 0; i < 4; i++) { int newX = top.x + X[i]; int newY = top.y + Y[i]; if (judge1(newX, newY)){ node0.x = newX; node0.y = newY; node0.step = top.step + 1;//新的节点,即将要访问的节点的更新 Q.push(node0); inq[newX][newY] = true; } } } return -1;}void testBFS2(){ cin >> n >> m; for (int x = 0; x < n; x++) { cin.get(); for (int y = 0; y < m; y++) { cin >> maze[x][y]; } maze[x][m + 1] = '\0'; } cin >> S.x >> S.y >> T.x >> T.y; S.step = 0; cout << BFS2() << endl;}
0 0
- (BFS)广度优先搜索例子:迷宫,寻找连块数
- 广度优先搜索BFS(迷宫问题)
- 迷宫问题(广度优先搜索BFS)
- 广度优先寻找迷宫!
- 广度优先搜索(BFS)
- 广度优先搜索(BFS)
- 广度优先搜索(BFS)
- 广度优先搜索(BFS)
- BFS(广度优先搜索)
- poj 3984 迷宫问题 BFS 图的广度优先搜索
- 搜索(广度优先搜索) BFS 1
- 搜索(广度优先搜索)BFS 2
- 广度优先搜索-BFS
- BFS广度优先搜索
- 广度优先搜索 BFS
- 广度优先搜索(BFS)
- 广度优先搜索(BFS)
- 广度优先搜索(BFS)
- Matlab中图片保存的5种方法
- Stm32利用SWD下载的设置
- 如何在原有的iOS项目中添加cordova
- 加工生产调度(Johnson算法 双机流水作业调度问题)
- Pyqt5系列(九)-基本布局管理
- (BFS)广度优先搜索例子:迷宫,寻找连块数
- JavaScript设计模式——单例模式
- ios 利用runtime打印类的所有属性
- JAVA中字节流与字符流的区别详解
- 常见排序算法汇总与分析(上)(交换排序与插入排序)
- 使用apt-get下载出错,Media change: please insert the disc labeled.
- 洛谷 P1071 潜伏者
- Swift 滑块 UISlider
- matlab读取avi视频问题总结(结合别人的解决方法)