迷宫问题

安利一发协会的这题
https://cn.vjudge.net/contest/299944#problem/C
为了这道题查了很多资料,看过很多题解,这道题让我学会了bfs的基本模板,还有简单的栈,这道题的思路就是先用bfs找到最优解,然后又栈保存前驱节点,最后逆序输出;
我的代码,第一次写这么长,,,,,,
#include
#include
#include //新学的头文件,队列需要用到
#include
#include //新学的头文件,栈需要用到
using namespace std;
int a[5][5];
int i=1;
bool b[100][100];
int d[4][2]={0,1,0,-1,1,0,-1,0};//四个方向
struct State
{
int x,y;
};
State f;
State e[100];
State p[6][6];//这个用结构体二维数组保存前驱节点
bool CheckState(State st)//bfs的入对条件
{
if(!b[st.x][st.y]&&a[st.x][st.y]0&&st.x>=0&&st.x<5&&st.y>=0&&st.y<5)
return 1;
else
return 0;
}
int print()
{
stacks;
State node;
node.x=4;
node.y=4;
while(node.x!=0 || node.y!=0)
{
s.push(node);
node=p[node.x][node.y];
}
node.x=0;
node.y=0;
s.push(node);
while(!s.empty())
{
printf("(%d, %d)\n",s.top());
s.pop();
}
}
void bfs(State s)
{
queue q;
State now,next;
q.push(s);
b[s.x][s.y]=1;
while(!q.empty())
{
now=q.front();
if(now.x
4 && now.y==4)
{
print();
return ;
}
for(int i=0;i<4;i++)
{
next.x=now.x+d[i][0];
next.y=now.y+d[i][1];
if(CheckState(next))
{
q.push(next);
p[next.x][next.y]=now;//将前驱节点保存在数组中
b[next.x][next.y]=1;
}
}
q.pop();
}
return ;
}
int main()
{
f.x=0,f.y=0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
cin >> a[i][j];
}
}
bfs(f);
return 0;
}
//队列是尾巴进头出,栈是先进后出;
queue中的基本用法有;
empty():判断是否为空;
pop ():移除前面的节点
front():返回前面的节点
push():加入队列,(对尾)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值