這一題需要思考的地方在於,如何把隕石墜落的時間考慮在bfs的過程中。參考別人思路,每個點地圖信息就存的是該點最早被破壞的時間。
這樣,我們在搜索的時候,注意已經用掉的時間 + 1 要小於 該點隕石墜落的時間就ok。
坑點:題意給出了隕石區,但沒有給出整個地圖的大小,所以走出隕石區就絕對安全。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 320 + 5;
int G[maxn][maxn];
const int dir[][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
const int inf =1e9;
bool vis[maxn][maxn];
struct node
{
int x, y, time;
node(int a, int b, int c):x(a), y(b), time(c){}
bool operator < (const node& a) const
{
return time > a.time;
}
};
void init()
{
memset(vis, 0, sizeof(vis));
for(int i = 0; i <= 304; i++)
for(int j = 0; j <= 304; j++)
G[i][j] = -1;
}
bool check(int x, int y)
{
if(x >= 0 &&y >= 0 && !vis[x][y]) return true;
return false;
}
void destory(int x, int y, int t)
{
if(G[x][y] != -1) G[x][y] = min(G[x][y], t);
else G[x][y] = t;
for(int i = 0; i < 4; i++)
{
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(check(tx, ty))
{
if(G[tx][ty] != -1) G[tx][ty] = min(G[tx][ty], t);
else G[tx][ty] = t;
}
}
}
int ans;
void bfs(int x, int y)
{
ans = inf;
priority_queue<node> q;
if(G[x][y] > 0)
q.push(node(x, y, 0));
if(G[x][y] == -1) ans = min(0, ans);
while(!q.empty())
{
node t = q.top();
q.pop();
for(int i = 0; i < 4; i++)
{
int tx = t.x + dir[i][0];
int ty = t.y + dir[i][1];
if(check(tx, ty))
{
vis[tx][ty] = 1;
if(G[tx][ty] == -1) ans = min(ans, t.time + 1);
else if(t.time + 1 < G[tx][ty])
q.push(node(tx, ty, t.time + 1));
}
}
}
printf("%d\n", ans == inf ? -1 : ans);
}
int main()
{
int n;
while(scanf("%d", &n) == 1)
{
init();
for(int i = 0; i < n; i++)
{
int x, y, t;
scanf("%d%d%d", &x, &y, &t);
destory(x, y, t);
}
bfs(0, 0);
}
return 0;
}