您的位置:首页 > 其它

HDU-1072:Nightmare

2013-01-15 11:02 267 查看
/*这道题的BFS中路径是可重复的,但有几个点不同,在重置时间那几个点上。
用BFS走过的路径是最短的,在到了重置时间点上,如果回过头来再走也不使时间增加的,
反而会增加出去的时间这样把重置时间的那几个点去掉后,由于时间是有限的。故可以再
有限步内结束。即避免了重复路径中不标志路径的死循环问题
*/
#include<iostream>
#include<queue>
const int N = 10;
using namespace std;
typedef struct
{
int i,j,t,pre;	//t为记录出去所需要花的时间。pre为炸弹爆炸剩余的时间
}Node;
int mp

;
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int m,n;
int bfs(int si,int sj)
{
queue<Node> q;
Node tmp;
Node p;
int di;
p.i = si, p.j = sj;
p.t = 0, p.pre = 6;
q.push(p);
while(!q.empty())
{
p = q.front();
q.pop();
if (mp[p.i][p.j]==3 && p.pre>0)	//在到达出口点时,时间必须大于0
return p.t;
for(di=0;di<4;di++)
{
tmp.i = p.i +dir[di][0];
tmp.j = p.j + dir[di][1];
tmp.t = p.t+1;
tmp.pre = p.pre-1;
//边界判断
if (tmp.i>=0 &&tmp.i<n &&tmp.j>=0 && tmp.j<m  && mp[tmp.i][tmp.j] && tmp.pre>0)	//在重置时间点上时,时间必须大于0
{
if (mp[tmp.i][tmp.j]==4 )
{
tmp.pre = 6;
mp[tmp.i][tmp.j] = 0;
}
else if(mp[tmp.i][tmp.j]==3)	//找到出口。直接退出
return tmp.t;
q.push(tmp);
}
}
}
return -1;
}

int main()
{
int t,si,sj;
cin>>t;
while(t--)
{
cin>>n>>m;
int i,j;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
cin>>mp[i][j];
if (mp[i][j]==2)
si = i, sj = j;
}
cout<<bfs(si,sj)<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: