Lintcode 598. Zombie in Matrix 解题报告

[Probelm] (link)

Given a 2D grid, each cell is either a wall 2, a zombie 1 or people 0 (the number zero, one, two).Zombies can turn the nearest people(up/down/left/right) into zombies every day, but can not through wall. How long will it take to turn all people into zombies? Return -1 if can not turn all people into zombies.

Example

Given a matrix:

0 1 2 0 0
1 0 0 2 1
0 1 0 0 0

return 2

[Idea]

BFS

Let's say initial zombie points are in the root level. The next level are those people points the current zombie points can reach.

[Code]

class Position {
public:
    int x, y;
    Position(int _x, int _y):x(_x), y(_y) {}
};


class Solution {
public:
    /**
     * @param grid  a 2D integer grid
     * @return an integer
     */
    int zombie(vector<vector<int>>& grid) {
        // Write your code here
        if(grid.empty() || grid[0].empty())
            return 0;
        int m = grid.size();
        int n = grid[0].size();

        queue<Position> q;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    q.push(Position(i, j));
                }
            }
        }
                    
        int d[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        int days = 0;
        while (!q.empty()) {
            days++;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                Position head = q.front();
                q.pop();
                for (int k = 0; k < 4; k++) {
                    int x = head.x + d[k][0];
                    int y = head.y + d[k][1];
                    if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) {
                        grid[x][y] = 1;
                        q.push(Position(x, y));
                    }
                }
            }
        }

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 0) {
                    return -1;
                }
            }
        }

        return days - 1; // -1 is needed here beccause in the last day of the loop, it must turn 0 people into zombie otherwise it wouldn't end here. This day doesn't count
    }
};

[Reference]

  1. Jiuzhang Solutions: Zombie in Matrix

转载于:https://www.cnblogs.com/casperwin/p/7456306.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值