题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1072
分析
这道题目涉及到bfs+回溯,所以不能像一般的bfs将经过的点进行标记,因为题目中炸弹的爆炸时长为6,所以只需要将经过的4的点进行标记,其他已经走过的点也只是在4这个点上最多回溯6步。
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
int a[10][10];
int n,m,ans;
int dir[][2] = {{-1,0},{1,0},{0,-1},{0,1}};
struct Node {
int x,y,step,time;
Node(int x,int y,int step,int time) {
this->x = x;
this->y = y;
this->step = step;
this->time = time;
}
};
bool isValid(int x,int y)//判断这个点是否可以走
{
return (x >= 0) && (x < n) && (y >= 0) && (y < m) && (a[x][y] != 0);
}
void bfs(int x,int y)
{
queue<Node> q;
q.push(Node(x,y,0,0));
while(!q.empty()) {
Node head = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int nx = head.x + dir[i][0];
int ny = head.y + dir[i][1];
if(isValid(nx,ny)) {
Node node(nx,ny,head.step + 1,head.time + 1);
if(a[nx][ny] == 3 && node.time < 6) {
ans = node.step;
return;
}
if(node.time < 6) {//如果小于6,那么还可以加入队列中
if(a[nx][ny] == 4) node.time = 0,a[nx][ny] = 0;//对4这个点进行标记,下次不再经过
q.push(node);
}
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--) {
scanf("%d%d",&n,&m);
int x,y;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++) {
scanf("%d",&a[i][j]);
if(a[i][j] == 2) x = i,y = j;
}
ans = 0;
bfs(x,y);
if(ans == 0) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}