#include <stdio.h>
#include <cstring>
#include <queue>using namespace std;
struct Node
{
int x, y, time, ans;
};queue<Node> q;
int map[9][9];
bool mark[9][9];
int n, m;
int sx, sy;
int dir[][2] = {1,0, -1,0, 0,1, 0,-1};int BFS()
{
Node start;
start.x = sx, start.y = sy, start.time = 6, start.ans = 0;
mark[sx][sy] = true;
q.push(start);
int nx, ny;
while(!q.empty())
{
Node cur = q.front();
q.pop();
if(map[cur.x][cur.y] == 3)
return cur.ans;
for(int i = 0; i < 4; i++)
{
nx = cur.x + dir[i][0];
ny = cur.y + dir[i][1];
if(nx < 0 || ny < 0 || nx >= n || ny >= m)
continue;
if(map[nx][ny] == 0)
continue;
Node tmp;
tmp.x = nx, tmp.y = ny, tmp.time = cur.time - 1, tmp.ans = cur.ans + 1;
if(tmp.time < 1)
continue;
if(map[nx][ny] == 4)
{
tmp.time = 6;
map[nx][ny] = 0; //重置器应该是只使用一次就应该会达到最优解,所以使用一次后,就标记为不可使用
}
q.push(tmp);
}
}
return -1;
}int main()
{
int c;
scanf("%d", &c);
while(c--)
{
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
scanf("%d", &map[i][j]);
if(map[i][j] == 2)
sx = i, sy = j;
}
memset(mark, 0, sizeof(mark));
while(!q.empty())
q.pop();
int res = BFS();
printf("%d\n", res);
}
return 0;
}
Nightmare HDU - 1072 (BFS)
最新推荐文章于 2021-08-16 10:55:55 发布