/*+++++++++++++++++++++++++++++++
+ 走迷宮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(深度優先改進)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.