//迷宫问题:求迷宫中从入口到出口的一条路径
//通常用的是“穷举求解”的方法,即从入口出发,顺某一方向向前探索,若能走通,则继续向前走;
//否则沿着原路返回,换一个方向再继续探索,直至所有可能的通路都探索到为止
//为了保证在任何位置上都能沿着原路返回,需要用一个先进先出的堆栈结构来保存从入口到当前位置的路径
/*
可以简单描述如下:
do{
若当前位置可通,
则{
将当前位置插入栈顶;//纳入路径
若该位置是出口位置,则结束;//求得路径存放在栈中
否则切换当前位置的相邻方块为新的当前位置;
}
否则,
若栈不空且栈顶位置尚有其他方向未经探索,
则设定新的当前位置为沿着顺时针方向旋转找到的栈顶位置的下一相邻块 ;
若栈不空但栈顶位置的四周均不通,
则{ 删去栈顶位置; //从路径中删除该通道块
若栈不空,则重新测试新的栈顶位置,
直至找到一个可通的相邻块或出栈至栈空;
}
}while(栈不空);
*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
const int MAX=100;
struct element{
short int row;
short int col;
short int dir;
};
struct offsets{
short int vert;
short int horiz;
};
offsets move[8]={
{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1} };//定义每个方向的偏移量并初始化
int maze[10][10]={ //初始化一个数组表示迷宫,最外围都是1,0表示通
{1,1,1,1,1,1,1,1,1,1},
{1,0,1,0,0,0,1,1,0,1},
{1,0,0,1,1,0,0,1,1,1},
{1,1,0,0,0,1,1,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,1,0,0,0,0,1,1,1,1},
{1,1,1,0,0,0,0,0,0,1},
{1,1,1,1,0,0,0,0,1,1},
{1,1,1,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
int mark[10][10]; //定义数组mark,用来标记该路径是否走过
const int ENTRY_ROW=1;//定义入口位置
const int ENTRY_COL=1;
const int EXIT_ROW=8;//定义出口位置
const int EXIT_COL=8;
void print(stack<element> &stk,int & i){
while(stk.size()>0){
element t=stk.top();
stk.pop();
print(stk,i+1);
printf("%5d:%5d%5d\n",i+1,t.row,t.col);
}
}
void path()//搜素出口
{
int i,j,row,col,next_row,next_col,dir,found=0;
element position;
//初始化mark数组,值为0代表该位置没走过,值为1代表该位置曾经走过
for( i=0;i<10;i++)
for(j=0;j<10;j++)
mark[i][j]=0;
mark[1][1]=1;;//入口起始位置为(1,1)
stack<element> stk;
element start={1,1,0};
stk.push(start);
while(stk.size()>0&&!found){
position=stk.top();
stk.pop();
row=position.row;
col=position.col;
dir=position.dir;
while(dir<8&&!found){
next_row=row+move[dir].vert;
next_col=col+move[dir].horiz;
if(next_row==EXIT_ROW&&next_col==EXIT_COL)
found=1;
else if(!maze[next_row][next_col]&&!mark[next_row][next_col]){
mark[next_row][next_col]=1;
position.row=next_row;position.col=next_col;
position.dir=++dir;
stk.push(position);
row=next_row;col=next_col;dir=0;
}else
dir++;
}
if(!found)
{
position=stk.top();
stk.pop();
}
}
if(found==1)
//print(stk,0);
{
int i=0;
printf("%5d:%5d%5d\n",++i,EXIT_ROW,EXIT_COL);
while(stk.size()>0){
element t=stk.top();
stk.pop();
printf("%5d:%5d%5d\n",++i,t.row,t.col);
}
}
}
int main()
{
path();
}
迷宫问题
最新推荐文章于 2023-12-19 09:13:10 发布