#include<iostream>
using namespace std;
/*
HDU1072
http://acm.hdu.edu.cn/showproblem.php?pid=1072
用x,y表示坐标,time表示距爆炸的时间
hash[x][y][time]则存储了到达这个状态的最少步数
最终的结果存储在hash[ex][ey][i]中
ex,ey为门所在的坐标,i从1到6,显然i为0时会被炸的粉身碎骨
*/
#define N 100
int n,m;
int map[8][8];
int hash[8][8][7];
//移动一步的四个方向
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
void dfs(int x,int y,int step,int time)
{
if(map[x][y]==4) time=6;//时间得到延长
if(hash[x][y][time]<=step) return;//这个方式没有以前好,舍去
hash[x][y][time]=step;
if(map[x][y]==3) return ;//到达终点,没有继续移动的必要
time--;
step++;
if(time)
{
for(int i=0;i<4;i++)
{
int xx=x+dx[i];
int yy=y+dy[i];
if(xx<0||xx>=n||yy<0||yy>=m||!map[xx][yy]) continue;//判断下一个坐标是否可行
dfs(xx,yy,step,time);
}
}
}
int main()
{
int i,j,sx,sy,ex,ey,s,t;
while(cin>>t)
while(t--)
{
cin>>n>>m;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
cin>>map[i][j];
if(map[i][j]==2) {sx=i;sy=j;}
if(map[i][j]==3) {ex=i;ey=j;}
}
memset(hash,N,sizeof(hash));
dfs(sx,sy,0,6);
s=N;
for(i=1;i<7;i++)
if(hash[ex][ey][i]<s) s=hash[ex][ey][i]; //曾在这里把ex,ey写成N,找了半天的错啊!
if(s==N) s=-1;//显然此时没有可能逃脱,按照题意把s赋值-1
cout<<s<<endl;
}
return 0;
}
HDU 1072
最新推荐文章于 2023-03-17 19:35:19 发布