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;}


其中对于结果的输出,使用了栈结构倒序输出。

 

谢谢指教。

原创粉丝点击