迷宫问题的非递归算法
#include<iostream.h>
#include<stdlib.h>
const m=6,n=8;
static int k=0;
int a[20],r[20],c[20];
int maze[m+2][n+2]={
1,1,1,1,1,1,1,1,1,1,
1,0,0,1,1,0,1,0,1,1,
1,1,0,0,1,1,0,0,0,1,
1,0,0,0,0,0,0,1,1,1,
1,1,1,0,1,1,0,0,0,1,
1,0,0,0,0,0,1,0,1,1,
1,1,0,1,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1};
int mark[m+2][n+2];
int move[4][2]={{0,1},//右
{1,0},//下
{0,-1},//左
{-1,0}//上
};
struct position{
int d;
int r;
int c;
};
struct LNode{
position e;
LNode *next;
};
void initstack(LNode* &HS)
{HS=NULL;}
int stackempty(LNode* HS)
{return HS==NULL;}
void push(LNode* &HS,int d1,int r1,int c1)
{
LNode* newptr=new LNode;
if(newptr==NULL){
cout<<"memory allocation failare"<<endl;
exit(1);}
newptr->e.d=d1;
newptr->e.c=c1;
newptr->e.r=r1;
newptr->next=HS;
HS=newptr;
}
position pop(LNode* &HS)
{
if(HS==NULL){
cout<<"linked stack is empty"<<endl;
exit(1);}
LNode *p=HS;
HS=HS->next;
position temp=p->e;
delete p;
return temp;
}
LNode *HS;
int seekpath(int x,int y)
{
initstack(HS);
int a=x;
int b=y;
int i=0,g,h;
do{
g=a+move[i][0];
h=b+move[i][1];
if((maze[g][h]==0)&&(mark[g][h]==0))
{
mark[g][h]=1;
push(HS,i,g,h);
if((g==m)&&(h==n))
return 1;
else{
a=g;
b=h;
i=0;}
}
else
i++;
if((i==4)&&!stackempty(HS))
{
pop(HS);
i=HS->e.d;
i++;
a=HS->e.r;
b=HS->e.c;
}
}while(!stackempty(HS));
return 0;
}
void main(void)
{
int i,j;
for(i=0;i<m+2;i++)
for(j=0;j<n+2;j++)
mark[i][j]=0;
mark[1][1]=1;
seekpath(1,1);
cout<<"迷宫路径为:"<<endl;
while(!stackempty(HS))
{cout<<"("<<HS->e.d<<","<<HS->e.r<<","<<HS->e.c<<")"<<" ";
pop(HS);}
cout<<endl;
cout<<"注释:括号中第一数表示从上一个位置到下一个位置的方向(0,1,2,3分别表示向东,南,西,北方向)"<<endl;
cout<<"第二个数和第三个数分别表示下一个位置的行坐标和列坐标"<<endl;
}
浙公网安备 33010602011771号