# C++利用队列（Queue）求解迷宫（Maze）中指定起点和终点间是否有最短路径，如果有的话输出所需步数，如果没有输出

#include <iostream.h>
#include <assert.h>
class Maze{
public:
class Point{
public:
Point():i(0),j(0){}
Point(int x,int y):i(x),j(y){}
Point(Point &x){
i=x.i;
j=x.j;
}
~Point(){}
public:
void Set(int x,int y){
i=x;
j=y;
}
Point operator+(Point &p){
return Point(i+p.i,j+p.j);
}
Point &operator=(Point &p){
i=p.i;
j=p.j;
return *this;
}
bool operator==(Point &p){
return i==p.i&&j==p.j;
}
bool operator!=(Point &p){
return i!=p.i||j!=p.j;
}
public:
int i;
int j;
};
public:
class Node{
public:
Node(){
next=NULL;
step=0;
}
Node(Point &p):pos(p){
next=NULL;
step=0;
}
Node(Point &p,int x):pos(p),step(x){}
Node &operator=(Node &obj){
pos=obj.pos;
step=obj.step;
return *this;
}
~Node(){}
public:
Point pos;
int step;
Node *next;
};
public:
class Queue{
public:
Queue(){
}
bool isEmpty(){
return false;
}
void Push(Node *obj){
if(isEmpty()){
return;
}
tail->next=obj;
tail=obj;
}
Node Pop(){
assert(!isEmpty());
Node temp;
return temp;
}
return temp;
}
~Queue(){}
public:
Node *tail;
};
public:
Maze(){
direction[0]=Point(1,0);
direction[1]=Point(0,1);
direction[2]=Point(-1,0);
direction[3]=Point(0,-1);
}
~Maze(){}
void Init();
void FindPath();
public:
Queue path;
Point start;
Point end;
Point present;
Point direction[4];
static int matrix[10][10];
int row,col;
};
int Maze::matrix[10][10]={0,0,0,0,0,0,0,0,0,0,
0,1,1,0,1,1,1,0,1,0,
0,1,1,0,1,1,1,0,1,0,
0,1,1,1,1,1,1,1,1,0,
0,1,0,0,0,1,1,1,1,0,
0,1,1,1,0,1,1,1,1,0,
0,1,0,1,1,1,0,1,1,0,
0,1,0,0,0,1,0,0,1,0,
0,0,0,0,0,0,0,0,0,0};//1表示可通过，0表示不能通过
void Maze::Init(){
cout<<"Input the rows:"<<endl;
cin>>row;
cout<<"Input the cols:"<<endl;
cin>>col;
cout<<"Input the starting point:"<<endl;
cin>>start.i>>start.j;
cout<<"Input the ending point:"<<endl;
cin>>end.i>>end.j;
//present.i=start.i;
//present.j=start.j;
present=start;
//path.Push(present);
}
void Maze::FindPath(){
path.Push(new Maze::Node(present));
matrix[present.i][present.j]=2;//2表示该节点已经被扫描
Maze::Node temp;
while(!path.isEmpty()){
temp=path.Pop();
//cout<<temp.pos.i<<' '<<temp.pos.j<<endl;
for(int i=0;i<4;++i){
present=temp.pos+direction[i];
if(matrix[present.i][present.j]==1&&present!=end){
path.Push(new Maze::Node(present,temp.step+1));
matrix[present.i][present.j]=2;
continue;
}
if(present==end){
cout<<"The path takes "<<temp.step+1<<" steps."<<endl;
return;
}
}
}
cout<<"There is no path."<<endl;
}
void main(){
Maze obj;
obj.Init();
obj.FindPath();
}

#### 迷宫求解【穷举求解法】

2016-11-23 21:40:58

#### 逃离迷宫

2017-08-17 16:02:54

#### hdu 1728 逃离迷宫

2016-07-18 19:06:04

#### hdu 1728 逃离迷宫（dFS+优先队列）

2013-08-17 20:23:12

#### 迷宫问题 DFS

2015-06-28 17:29:04

#### 问题 H: 逃出迷宫

2017-03-06 21:10:27

#### 逃出迷宫

2017-03-10 19:08:05

#### 回溯法(backtracking)解决平衡集合问题

2013-05-12 15:34:11

#### Beginning C++ Game Programming 无水印pdf

2018年05月09日 0B 下载