您的位置:首页 > 其它

HDU 1072 Nightmare

2014-06-09 21:03 281 查看
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1072

题意比较好理解,这里就不多做解释了,像我英语这么差的人都读的懂,别人更应该就没什么了

。看到题目肯定想到是BFS好写,是一道限时的题目,但是当你到有Bomb-Rest-Equipment的地方时,时间又会恢复到6秒,所以走的步数最少不一定用的时间就最少,题目是要求出最短时间,所以我在写结构体时即定义了时间,又定义了步数。写的时候还是出现了很多问题,唉,Wa了好多次,后来参考了网上的代码,看到了他们开了一个数组,代表走到这一点还剩余的最大时间,用if(next.time>1&&T[next.x][next.y]<next.time)进行判断,然后过了。都是泪啊。不过个人感觉这个题目还是挺值的做的。。很适合初学者。

代码:

#include <cstring>
#include <cstdio>
#include <queue>

using namespace std;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int map[9][9];
int T[9][9];
int si,sj;
int n,m;
struct point
{
int x,y,time,step;
}start;

int BFS(int a,int b)
{
queue<point> q;
point cur,next;
int i;

start.x=a;
start.y=b;
start.step=0;
start.time=6;

q.push(start);

while(!q.empty())
{

cur=q.front();
q.pop();

for(i=0;i<4;i++)
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
next.time=cur.time-1;
next.step=cur.step+1;

if(map[next.x][next.y]==3)
return next.step;

if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m)
{
if(map[next.x][next.y]!=0)
{
if(map[next.x][next.y]==4&&next.time>0)
next.time=6;
if(next.time>1&&T[next.x][next.y]<next.time)
{
// If Ignatius get to the exit when the exploding time turns to 0, he can't get out of the labyrinth

//map[next.x][next.y]=0;    题目规定走过的还可以走的。
T[next.x][next.y]=next.time;
q.push(next);
}
}
}

}
}
return -1;
}

int  main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);

int i,j,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);

for(i=0;i<n;i++)
{

for(j=0;j<m;j++)
{

scanf("%d",&map[i][j]);
if(map[i][j]==2)
{

si=i;
sj=j;
}
}

}

memset(T,0,sizeof(T));
T[si][sj]=6;
map[si][sj]=0;

int count=BFS(si,sj);

printf("%d\n",count);
}
return 0;
}


 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BFS