Description
Bessie hears that an extraordinary meteor shower is coming; reports say that these meteors will crash into earth and destroy anything they hit. Anxious for her safety, she vows to find her way to a safe location (one that is never destroyed by a meteor) . She is currently grazing at the origin in the coordinate plane and wants to move to a new, safer location while avoiding being destroyed by meteors along her way.
The reports say that M meteors (1 ≤ M ≤ 50,000) will strike, with meteor i will striking point (Xi, Yi) (0 ≤ Xi ≤ 300; 0 ≤ Yi ≤ 300) at time Ti (0 ≤ Ti ≤ 1,000). Each meteor destroys the point that it strikes and also the four rectilinearly adjacent lattice points.
Bessie leaves the origin at time 0 and can travel in the first quadrant and parallel to the axes at the rate of one distance unit per second to any of the (often 4) adjacent rectilinear points that are not yet destroyed by a meteor. She cannot be located on a point at any time greater than or equal to the time it is destroyed).
Determine the minimum time it takes Bessie to get to a safe place.
Input
* Line 1: A single integer: M
* Lines 2..M+1: Line i+1 contains three space-separated integers: Xi, Yi, and Ti
Output
* Line 1: The minimum time it takes Bessie to get to a safe place or -1 if it is impossible.
Sample Input
4 0 0 2 2 1 2 1 1 2 0 3 5
Sample Output
5
题解:预处理流星炸下来的时间长度和范围。然后bfs找到相应没有流星砸落或燃烧的地方。
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
const int INF = 0x7fffffff;
const int maxn = 310;
struct Node{
int x,y,t;
Node(int a,int b,int c){x=a;y=b;t=c;}
};
int M;
int pic[maxn][maxn];
bool vis[maxn][maxn];
int dirx[4] = {0,1,0,-1};
int diry[4] = {1,0,-1,0};
void init(){
for(int i = 0; i < maxn; i++)
for(int j = 0; j < maxn; j++){pic[i][j]=INF;vis[i][j]=false;}
int X,Y,T;
for(int i = 0; i < M; i++){
scanf("%d%d%d",&X,&Y,&T);
if(pic[X][Y] > T) pic[X][Y] = T;
if(pic[X+1][Y] > T)pic[X+1][Y] = T;
if(pic[X][Y+1] > T)pic[X][Y+1] = T;
if(X-1>=0 && pic[X-1][Y] > T) pic[X-1][Y] = T;
if(Y-1>=0 && pic[X][Y-1] > T) pic[X][Y-1] = T;
}
}
int bfs(){
queue<Node> Q;
Q.push(Node(0,0,0));
vis[0][0] = true;
while(!Q.empty()){
Node temp = Q.front();Q.pop();
for(int i = 0; i < 4; i++){
int x = temp.x+dirx[i];
int y = temp.y+diry[i];
int t = temp.t+1;
if(x<0||y<0) continue;
if(pic[x][y] <= t || vis[x][y]) continue;
vis[x][y] = true;
if(pic[x][y] == 0x7fffffff) return t;
Q.push(Node(x,y,t));
}
}
return -1;
}
int main(){
while(cin>>M){
int sum = 0;
init();
if(pic[0][0] != 0x7fffffff) sum = bfs();
cout<<sum<<endl;
}
return 0;
}