数据结构大实习——迷宫路径

#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

const int maxn=500;

typedef struct node
{
int x,y,i;
} node;

typedef struct stack
{
node num[maxn];
int top;
} Stack;

void InitStack(Stack &s)
{
s.top=-1;
return ;
}

bool StackEmpty(Stack &s)
{
if(s.top==-1)
return true;
else
return false;
}

bool StackFull(Stack &s)
{
if(s.top==maxn-1)
return true;
else
return false;
}

node StackTop(Stack &s)
{
return s.num[s.top];
}

void StackPush(Stack &s,node a)
{
s.num[++s.top]=a;
return ;
}

void StackPop(Stack &s)
{
s.top--;
return ;
}

int map[maxn][maxn];
bool vis[maxn][maxn];
int nx[4]= {-1,0,1,0};
int ny[4]= {0,-1,0,1};

bool dfs(Stack &s,node in,int n,int m,node ans[],int &cnt)
{

memset(vis,0,sizeof(vis));
InitStack(s);
in.i=0;
if(!StackFull(s))
StackPush(s,in);
ans[cnt++]=in;
while(!StackEmpty(s))
{
node tmp=StackTop(s),ne;
vis[tmp.x][tmp.y]=true;
bool flag=false;
for(int &i=tmp.i;i<4;i++)
{
ne.x=tmp.x+nx[i];
ne.y=tmp.y+ny[i];
ne.i=0;
if(ne.x>=1&&ne.x<=n&&ne.y>=1&&ne.y<=m&&(!vis[ne.x][ne.y])&&map[ne.x][ne.y]!=1)
{
vis[ne.x][ne.y]=true;
flag=true;
StackPush(s,ne);
ans[cnt++]=ne;
if(map[ne.x][ne.y]==3)
return 1;
break;
}
}
if(flag)
continue;
else
{
StackPop(s);
cnt--;
}
}
return 0;
}

int main()
{
int n,m;
Stack s;
node ans[maxn];
while(cin>>n>>m)
{
node in;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
{
cin>>map[i][j];
if((i==1||i==n||j==1||j==m)&&map[i][j]==2)
in.x=i,in.y=j;
}
int cnt=0;
if(dfs(s,in,n,m,ans,cnt))
{
for(int i=0;i<cnt;i++)
{
cout<<"("<<ans[i].x<<","<<ans[i].y<<")";
i!=cnt-1?cout<<"->":cout<<endl;
}
}
else
cout<<"node path"<<endl;
}
return 0;
}
/*0是可走
1代表墙
2代表入口
3代表出口
4 4
1 2 1 1
1 0 0 1
1 1 0 1
1 1 0 3
5 5
1 2 1 3 1
1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 0 0 1
4 4
1 2 1 3
1 0 1 0
1 0 1 0
1 1 0 0
*/

  

原文地址:https://www.cnblogs.com/wyhbadly/p/10132081.html