栈的回退思想实现深度优先搜索

迷宫问题求解(引用了深度优先搜索的回退的思想,只不过用循环和栈代替递归实现)
因此也有深搜的一个缺点,深搜在第一次找到终点的时候会结束,但是难以求解最少步数,因此再求最小步数的时候,我们常用广度优先搜索
#include"iostream"
#include"cstdio"
#include"cstdlib"
using namespace std;


struct node
{
int x;
int y;
int dir;
};
typedef struct node p;
p stack[100];
int top=0;
p mo;


int sum=0;
int book[100][100];
char map[100][100];
p start,end;
int n,m;


bool empty()
{
if(top==0)
{
return 1;
}
else
{
return 0;
}
}


void show()
{
for(int i=1;i<=top;i++)
{
printf("(%d,%d) ",stack[i].x,stack[i].y);
}
cout<<endl<<sum<<endl;
}


p nextpos(p mo,int dir)
{
p k;
if(dir==1)
{
k.y=mo.y+1;
k.x=mo.x;
k.dir=1;
}
if(dir==2)
{
k.x=mo.x+1;
k.y=mo.y;
k.dir=1;
}
if(dir==3)
{
k.y=mo.y-1;
k.x=mo.x;
k.dir=1;
}
if(dir==4)
{
k.x=mo.x-1;
k.y=mo.y;
k.dir=1;
}
return k;
}


bool pass(p mo)
{
if(mo.x>n||mo.y>m||map[mo.x][mo.y]=='#'||book[mo.x][mo.y]==1)
{
return false;
}
else
{
return true;
}
}


void init()
{
for(int i=1;i<=100;i++)
{
for(int j=1;j<=100;j++)
{
map[i][j]='#';
}
}
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>map[i][j];
}
}
cout<<endl;
cin>>start.x>>start.y>>end.x>>end.y;
start.dir=1;
}


int main()
{
init();
mo=start;
do
{
if(pass(mo))
{
top++;
stack[top]=mo;
book[mo.x][mo.y]=1;
mo.dir=1;
if(mo.x==end.x&&mo.y==end.y)
{
show();
exit(0);
}
else
{
mo=nextpos(mo,mo.dir);
sum++;
}
}
else
{
if(stack[top].dir<4)
{
stack[top].dir++;
mo=nextpos(stack[top],stack[top].dir);
}
else
{
while(stack[top].dir>=4)
{
top--;
//book[stack[top+1].x][stack[top+1].y]=0;
sum--;
}
stack[top].dir++;
mo=nextpos(stack[top],stack[top].dir);
}
}
}while(!empty());
cout<<"no way to go out!"<<endl; 
return 0;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值