hdu 1072 Nightmare 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1072
BFS
题目大意:Ignatius做恶梦,梦见自己在一个迷宫里,迷宫地图给出,问能否走出。(怎么这类题的题意都这么千篇一律)
输入分析:地图中有0、1、2、3、4五种标记。0代表不可走(墙);1代表平地;2代表起点;3代表终点;4代表炸弹重置点(场景里是有炸弹的,炸弹会在时间跑完时爆炸,毁灭全图,初始时间为6,每走一格减1单位时间,炸弹重置点可以重置炸弹,把时间置回6)
题目分析:BFS且直接利用队列,细节详见code。
code:
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
int a[9][9],n,m,sx,sy,dir[4][2]={1,0,-1,0,0,1,0,-1};
struct node
{
int x,y,s,t;
};//这个分号不能少
int bfs()//bfs函数只跑一遍,这是跟dfs最明显的差异
{//准备工作:用队列,还需要两个变量来具体处理
queue<node>que;
node first,next;
first.x=sx;
first.y=sy;
first.s=0;
first.t=6;
que.push(first);
a[sx][sy]=0;
while(!que.empty())
{
first=que.front();
que.pop();
for(int i=0;i<4;i++)//用for循环可节省代码量,且思路清晰
{
next.x=first.x+dir[i][0];
next.y=first.y+dir[i][1];
if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&a[next.x][next.y]!=0&&first.t>1)
{
if(a[next.x][next.y]==3)return first.s+1;
else if(a[next.x][next.y]==1)
{
next.s=first.s+1;
next.t=first.t-1;
que.push(next);
//a[next.x][next.y]=0;根据题意,这一句是不需要的
}
else if(a[next.x][next.y]==4)
{
next.s=first.s+1;
next.t=6;
que.push(next);
a[next.x][next.y]=0;
}
}
}
}
return -1;
}
int main()
{
int t,i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]==2)sx=i,sy=j;
}
}
printf("%d\n",bfs());
}
}
本题bfs函数详解:
/*
逐句解释bfs:
int bfs{
准备工作:建立队列que,两个节点first,next
初始化first为起始点并进队,地图上起点赋0
while(队列不为空)
{
队首元素赋给first后出列;
for(向四个方向分别访问地图上的点)
{
if(这是个可访问点)
{
情况一:走到出口,出去(返回步数);
情况二:普通平地,走上去;
情况三:炸弹重置点,重置;
}
}
}
循环结束还没有找到出口,返回-1;
}
*/
PS:BFS第一弹,代码完全参考别人的,自己仅看懂而已,下一步要自己写了……
PPS:这道题还需要注意的是,炸弹重置点走完就不能再走了,但其它点还是可以再走的(具体意义:当你快走投无路的时候,你可以先去就近的重置点先重置一下炸弹,然后回来继续走)