题意:
2是起点,3是终点,1是可以走的路,0是不可通过的路,4是一个炸弹重置设备,可以让炸弹的时间变成6(前提是你至少有1的时间用来重置),在2的时候炸弹的时间会变成6,每走一步就会消耗一单位的时间,到0你就gg了。问你能不能到达终点,如果能,输出最早的时间。
思路:
其实也是一个比较板子的题目,但是他这里每一个位置都会有一个时间,所以这次的dfs跟其他的dfs还有点不一样:我们可以想这么一个问题:
a点的时间为xa,b点的时间为xb,
如果,(因为a点到b点需要消耗1单位时间),那么肯定是不如之前的结果的。
那么我们可以int st数组,用来存储走到当前点的剩余的最大的时间,如果当前点的时间<要走的时间的话,就可以把这个点加入进去。
首先如果当前点的时间为1的话,如果当前点不是终点的话,那么只要往四周走都会变成0也就是直接gg,所以直接continue:
然后是如果走到4的话,直接把这个点的时间赋值为6就可以了。
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
#include<cstdio>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <math.h>
#include<vector>
#include<queue>
#include<map>
#define sc_int(x) scanf("%d", &x)
#define sc_ll(x) scanf("%lld", &x)
#define pr_ll(x) printf("%lld", x)
#define pr_ll_n(x) printf("%lld\n", x)
#define pr_int_n(x) printf("%d\n", x)
#define ll long long
using namespace std;
const int N=1000000+100;
int n ,m,h;
int cnt[9][9];
int st [9][9];
int tx,ty,ex,ey;
int dx[5]={0,1,0,-1,0};
int dy[5]={0,0,-1,0,1};
struct lk
{
int x;
int y;
int time;
int cnt;
};
void init(lk &k){k.x=tx,k.y=ty,k.cnt=0,k.time=6,st[tx][ty]=6;}//初始化
void bfs( )
{
lk k;
init(k);
queue<lk>q;
q.push(k);
while(q.size())
{
lk k =q.front(),now;
q.pop();
if(k.x==ex&&k.y==ey){
cout<<k.cnt<<endl;
return ;
}
if(k.time==1)continue;
for(int i =1;i<=4;i++)
{
int x=k.x+dx[i],y=k.y+dy[i];
if(x<1||x>n||y<1||y>m)continue;//边界
if(st[x][y]>=k.time||cnt[x][y]==0)continue;//判断条件
now.x=x,now.y=y,now.cnt=k.cnt+1;
if(cnt[x][y]==4)
now.time=6;
else
now.time=k.time-1;
st[x][y]=now.time;
q.push(now);
}
}
cout<<"-1\n";
}
int main()
{
int t;
sc_int(t);
while(t--)
{
memset(st,0,sizeof st);//初始化
sc_int(n),sc_int(m);
for(int i =1;i<=n;i++)
for(int j =1;j<=m;j++){
sc_int(cnt[i][j]);
if(cnt[i][j]==2) tx=i,ty=j;
if(cnt[i][j]==3) ex=i,ey=j;
}
bfs();
}
return 0;
}