问题来源《数据结构》(c语言版)主编 秦锋 P86
求迷宫的最短路径:现在设计一个算法找一条从迷宫入口到出口的最短路径。此程序和书上的思路不一样。。。。。。
//这个算法是队列,递归综合考察
#include<iostream>
#include<vector>
#define MAXSIZE 100
using namespace std;
int Maze[12][12]=
{
{1,1,1,1,1, 1,1,1,1,1, 1,1},
{1,0,0,0,0, 0,0,0,0,0, 0,1},
{1,0,1,1,1, 0,1,1,1,1, 0,1},
{1,0,0,0,1, 0,0,0,0,1, 1,1},
{1,0,1,0,1, 1,1,1,0,0, 0,1},
{1,0,1,0,0, 0,1,1,1,1, 0,1},
{1,0,1,0,1, 1,1,1,1,1, 0,1},
{1,0,1,0,1, 1,1,1,0,0, 0,1},
{1,0,1,0,0, 0,0,0,0,1, 0,1},
{1,0,1,1,1, 1,1,1,1,1, 0,1},
{1,0,0,0,0, 0,0,0,0,0, 0,1},
{1,1,1,1,1, 1,1,1,1,1, 1,1}
};//上面有三条路径,没有环路,求出最短路径
//定义一个队列------------------------------------》顺序无循环队列
typedef struct
{
int x; //坐标x
int y;
int pre; //存放前一个点,pre等于data【x】中的x 回溯的思路慢慢清晰
}sqtype;
typedef struct
{
sqtype data[MAXSIZE];
int front; //头
int rear; //尾
}SeqQueue,*PSeqQueue;
//起始点
int x_start=1;
int y_start=1;
//终止点
int x_end=7;
int y_end=10;
//定义前进方向
int Ahead[4][2]=
{
{0,-1},
{1, 0},
{0, 1},
{-1,0}
};
//标记
//bool flag[4]={false,false,false,false};
vector<sqtype> reversal;
//函数
void Path_find(PSeqQueue Path_Queue, int num)
{
int f_num=num;
if((Path_Queue->data[Path_Queue->rear].x!=x_end)||(Path_Queue->data[Path_Queue->rear].y!=y_end))
{
int i=0;
while(i<4)
{
//if(Maze[Path_Queue->data[num].x+Ahead[i][0]]
//提高可读性
// int x,y;
int x=Path_Queue->data[f_num].x+Ahead[i][0];
int y=Path_Queue->data[f_num].y+Ahead[i][1];
if(Maze[x][y]!=1)
{
Maze[x][y]=1;
Path_Queue->rear++;
Path_Queue->data[Path_Queue->rear].x=x;
Path_Queue->data[Path_Queue->rear].y=y;
Path_Queue->data[Path_Queue->rear].pre=f_num;
//Path_Queue->rear=num;
//cout<<"("<<x<<","<<y<<")"<<endl;
}
i++;
}
if(Path_Queue->front!=Path_Queue->rear)
{
Path_Queue->front++;
Path_find(Path_Queue, Path_Queue->front);//递归寻找路径
}
else
{cout<<"error"<<endl;}
}
else
{
while((Path_Queue->data[Path_Queue->rear].x!=x_start) ||(Path_Queue->data[Path_Queue->rear].y!=y_start))
{
//cout<<"("<<Path_Queue->data[Path_Queue->rear].x<<","<<Path_Queue->data[Path_Queue->rear].y<<")";
// cout<<endl;
reversal.push_back(Path_Queue->data[Path_Queue->rear]);
Path_Queue->rear=Path_Queue->data[Path_Queue->rear].pre;
}
//cout<<"("<<Path_Queue->data[Path_Queue->rear].x<<","<<Path_Queue->data[Path_Queue->rear].y<<")";
reversal.push_back(Path_Queue->data[Path_Queue->rear]);
}
}
void main()
{
PSeqQueue Init_Queue=new SeqQueue;
//初始化
Init_Queue->data[0].x=x_start;
Init_Queue->data[0].y=y_start;
Init_Queue->data[0].pre=NULL;
Init_Queue->front=0;
Init_Queue->rear=0;
Maze[x_start][y_start]=1;
Path_find(Init_Queue,0);
//显示
vector<sqtype>::iterator iter=reversal.end(); //end()函数返回长度+1的地址,
int len=reversal.size();
for(int i=1;i<len+1;i++) //注意这里为啥从一开始,而不是从零开始,因为end()函数返回长度+1的地址
{
cout<<"("<<(iter-i)->x<<","<<(iter-i)->y<<")"<<endl;
}
}