C++ queue应用之电路布线(迷宫的最短路径)
来源:互联网 发布:js classname事件 编辑:程序博客网 时间:2024/06/05 02:59
假如我们给定一个如下所示的迷宫,蓝色表示边界或不可通过的区域(用1表示),白色表示可以通过的区域(用0表示),绿色表示起始点,红色表示到达的终点。这样可以用一个数组表示这个Maze。
我们要做的是找到从起始点到终点的最短路径。要求用4领域可通过。
下面是我用 Queue 实现的寻径算法:
#include "stdafx.h"#include <iostream>#include "Queue.h"#include <stack>#include <iomanip>using namespace std;class Position{public:Position(int x=0,int y=0):row(x),col(y){}int row;int col;};const int m=7;const int n=8;int Maze[m+2][n+2] = { 1,1,1,1,1,1,1,1,1,1, 1,0,0,0,0,0,1,0,0,1, 1,0,1,1,1,0,0,1,0,1, 1,0,0,1,0,1,0,0,0,1, 1,1,0,1,0,1,1,0,1,1, 1,0,0,0,0,0,0,0,0,1, 1,0,1,1,0,1,1,0,1,1, 1,0,0,0,0,0,0,0,0,1, 1,1,1,1,1,1,1,1,1,1};int _tmain(int argc, _TCHAR* argv[]){Position offset[4] = {Position(0,1),Position(1,0),Position(0,-1),Position(-1,0)};Position start(1,1);Position finish(7,8);Maze[start.row][start.col]=2; // mask the start point that it's visited with >=2 . 0 is not visited. 1 is can not pass.Position here,nbor;Queue<Position> myqueue(60);myqueue.EnQueue(start);while(!myqueue.IsEmpty()){// we view the half result in processingfor(int a=0;a<9;a++){for(int b=0;b<10;b++)cout<<setw(2)<<Maze[a][b]<<" ";cout<<endl;}cout<<endl;myqueue.DeQueue(here);for(int i=0;i<4;i++){nbor.row = here.row+offset[i].row;nbor.col = here.col+offset[i].col;if(Maze[nbor.row][nbor.col]==0) // which is not visited, and can be pass.{ Maze[nbor.row][nbor.col]=Maze[here.row][here.col]+1;if(nbor.row==finish.row && nbor.col==finish.col){break;}myqueue.EnQueue(nbor);}}if(nbor.row==finish.row && nbor.col==finish.col){cout<<"We find the min-distance path!"<<endl;break;}}// we construct the path from the matrixint pathlen = Maze[finish.row][finish.col]-2;stack<Position> mypath;here = finish;for(int j=pathlen-1;j>=0;j--){mypath.push(here);for(int i=0;i<4;i++){nbor.row = here.row+offset[i].row;nbor.col = here.col+offset[i].col;if(Maze[nbor.row][nbor.col]==j+2)break;}here = nbor;}mypath.push(start);while(!mypath.empty()){Position tmp = mypath.top();mypath.pop();cout<<"("<<tmp.row<<","<<tmp.col<<")"<<endl;}system("pause");return 0;}
其中对于结果的输出,使用了栈结构倒序输出。
谢谢指教。
- C++ queue应用之电路布线(迷宫的最短路径)
- 寻找电路布线最短路径(Queue)
- 分支限界法 求电路布线的最短路径
- 迷宫的最短路径(BFS的简单应用)
- 迷宫的最短路径 代码(C++)
- 迷宫的最短路径 (BFS)
- 数据结构::迷宫(二)--栈的一个应用(求迷宫最短路径)
- 迷宫的最短路径
- 迷宫的最短路径
- 迷宫的最短路径
- 迷宫的最短路径
- 迷宫的最短路径
- 迷宫的最短路径
- 迷宫的最短路径
- 迷宫的最短路径
- 迷宫的最短路径
- 编程算法 - 迷宫的最短路径 代码(C++)
- c语言,迷宫最短路径
- 屏幕取词技术实现原理与关键源码
- POJ 2195 Going Home
- uva10827 - Maximum sum on a torus(圆环上的最大和)
- 黑马程序员_异常
- T-SQL逻辑查询处理的各个阶段
- C++ queue应用之电路布线(迷宫的最短路径)
- java语言程序设计 14.2 comparable
- mysql数据库复习加强
- 微软2013年暑期实习招聘笔试回忆[转载]
- 正则表达式(二)
- Warning: stream_socket_server() has been disabled for security reasons
- EOI
- cocos2d-x 图块坐标与世界坐标剖析
- 解决:在点击用户退出登录时,再按浏览器的后退按钮,仍然能够看到之前的页面