Poj 3669 Meteor Shower

思路,本题是很单纯的BFS,类似于用BFS求最短路径,用二维数组,来存放每个点被炸毁的时间,这类似于简单题里面,用二维数组来存放某个点能不能通过(是路障还是路),然后在BFS里面,判断一个点能不能入队,有一个条件是,走到它的时间小于它被炸毁的时间。如果走到一个点,这个点矩阵里面存的是初始化的无穷大,那么就走出去了。
需要注意,判断一个点的坐标是否合法不能限制在300,因为炸到300,那么301也被炸坏了,所以要开大一点。同时也有可能一步还没走就被炸死,需要特判。

#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
struct node{
    int x, y, layer;
};
const int INF = 1000000000;
int m, c1, c2, c3, matrix[310][310], X[4] = {0, 1, 0, -1}, Y[4] = {-1, 0, 1, 0};
bool inQ[310][310] = {};
bool judge(int x, int y)
{
    if(x >= 0 && x <= 305 && y >= 0 && y <= 305) return true;
    else return false;
}
int BFS(int x, int y)
{
    inQ[y][x] = true;
    queue<node> q;
    node s;
    s.x = x, s.y = y, s.layer = 0;
    q.push(s);
    while(q.empty() == false){
        node now = q.front();
        q.pop();
        if(matrix[now.y][now.x] == INF){
            return now.layer;
        }
        for(int i = 0; i < 4; i++){
            int tempx = now.x + X[i], tempy = now.y + Y[i];
            if(judge(tempx, tempy) == true && inQ[tempy][tempx] == false && now.layer + 1 < matrix[tempy][tempx]){
                inQ[tempy][tempx] = true;
                s.x = tempx, s.y = tempy, s.layer = now.layer + 1;
                q.push(s);
            }
        }
    }
    return -1;
}
int main()
{
    while(scanf("%d", &m) != EOF){
        fill(matrix[0], matrix[0] + 310 * 310, INF);
        fill(inQ[0], inQ[0] + 310 * 310, false);
        for(int i = 0; i < m; i++){
            scanf("%d%d%d", &c1, &c2, &c3);
            if(c3 < matrix[c2][c1]) matrix[c2][c1] = c3;
            for(int j = 0; j < 4; j++){
                int tempx = c1 + X[j], tempy = c2 + Y[j];
                if(judge(tempx, tempy) == true && c3 < matrix[tempy][tempx]) matrix[tempy][tempx] = c3;
            }
        }
        if(matrix[0][0] == 0) printf("-1\n");
        else printf("%d\n", BFS(0, 0));
    }
    return 0;
}
发布了30 篇原创文章 · 获赞 0 · 访问量 378

猜你喜欢

转载自blog.csdn.net/qq_33942309/article/details/105418820