/*+++++++++++++++++++++++++++++++
+ 走迷宫21(C改进版)
+
+ 深度遍历算法,输出所有路经。
+主要思想用栈,(用list栈代替)。
+author:zhouyongxyz 2013-4-14 9:00
++++++++++++++++++++++++++++++++++++++++++*/
#include <cstdio>
#include <algorithm>
#include <list>
using namespace std;
#define M 5
#define N 6
struct node
{
int x,y;
node(){x=y=0;};
};
int vis[M][N];
static int dx[]={-1,1,0,0};
static int dy[]={0,0,-1,1};
void print_ans(list<node> s);
int main()
{
int a[M][N]={
{1,0,1,1,1,1},
{1,0,1,0,0,0},
{1,0,0,0,1,0},
{1,1,1,0,0,0},
{1,1,1,0,1,1}
};
list<node> list;
struct node u,v;
int flag;
u.x=0,u.y=1;
list.push_back(u);
while(!list.empty())
{
u=list.back();
if(u.x==3&&u.y==5)
{
print_ans(list);
vis[u.x][u.y]=0;
/*
回退两步,这样代码容易实现,这也符合正常的逻辑思维,一步就能
到达目的地,没有必要要绕一大圈。
*/
list.pop_back();
list.pop_back();
u=list.back();
}
flag=0;
for(int i=0;i<4;i++)
{
int newx=u.x+dx[i],newy=u.y+dy[i];
if(newx>=0&&newx<M&&newy>=0&&newy<N&&!vis[newx][newy]&&a[newx][newy]==0)
{
v.x=newx;
v.y=newy;
list.push_back(v);
flag=1;
vis[newx][newy]=1;
break;
}
}
if(!flag)
list.pop_back();
}
return 0;
}
void print_ans(list<node> s)
{
struct node n;
while(!s.empty())
{
n=s.front();
printf("(%d,%d)-> ",n.x,n.y);
s.pop_front();
}
printf("(find)\n");
}
走迷宫21(深度优先改进)
猜你喜欢
转载自blog.csdn.net/ZHOUYONGXYZ/article/details/8798924
今日推荐
周排行