您的位置:首页 > 其它

POJ 3669 Meteor Shower BFS

2014-07-16 16:08 197 查看
//624K	63MS
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

struct node{
int x, y, t;
};

const int INF = 1e9 + 7;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
int map[305][305];
bool vis[305][305];

inline bool ok(int x, int y){
if(x >= 0 && y >= 0) return 1;
else return 0;
}

inline void crash(int x, int y, int t){
if(t < map[x][y]) map[x][y] = t;
if(t < map[x+1][y]) map[x+1][y] = t;
if(t < map[x][y+1]) map[x][y+1] = t;
if(x > 0 && t < map[x-1][y]) map[x-1][y] = t;
if(y > 0 && t < map[x][y-1]) map[x][y-1] = t;
}

void bfs(){
memset(vis, 0, sizeof(vis));
queue<node> q;
node h, n;
h.x=0, h.y=0, h.t=0; //在OJ上不能用{...}赋值,编译错。。
q.push(h);
vis[0][0] = 1;
while(!q.empty()){
h = q.front();
q.pop();
if(map[h.x][h.y] == INF){
printf("%d\n", h.t);
return;
}
for(int i=0; i<4; i++){
n.x = h.x + dx[i];
n.y = h.y + dy[i];
n.t = h.t + 1;
if(ok(n.x, n.y))
if(!vis[n.x][n.y] && map[n.x][n.y] > n.t){
q.push(n);
vis[n.x][n.y] = 1;
}
}
}
printf("-1\n");
}

int main(){
int m;
while(scanf("%d", &m) != EOF){
for(int i=0; i<305; i++)
for(int j=0; j<305; j++)
map[i][j] = INF;
int x, y, t;
while(m--){
scanf("%d %d %d", &x, &y, &t);
crash(x, y, t);
}
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: