LintCode 598: Zombie in Matrix (BFS好题)

  1. Zombie in Matrix
    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
Example 1:

Input:
[[0,1,2,0,0],
[1,0,0,2,1],
[0,1,0,0,0]]
Output:
2
Example 2:

Input:
[[0,0,0],
[0,0,0],
[0,0,1]]
Output:
4

解法1:BFS
将所有的zombie同时放入queue中,然后就跟正常bfs一样了。
注意:

  1. 最后返回round-1,因为最后返回的时候会多算一空的一轮。
  2. 当最后仍有people时,返回-1。这种情形就是people被封闭起来,zombie进不去。
  3. 本来我想当某个round没有发现people时就返回当前round,这样round就不会多加1。但是不能直接返回当前round,因为可能有people没发现,参考2)。
  4. 如果要返回round, q.size()一定要保存下来,因为queue的长度会变。
    代码如下:
class Solution {
public:
    /**
     * @param grid: a 2D integer grid
     * @return: an integer
     */
    int zombie(vector<vector<int>> &grid) {
        int m = grid.size();
        if (m == 0) return 0;
        int n = grid[0].size();
        
        queue<pair<int, int>> q;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) q.push({i, j});
            }
        }
        
        vector<int> dx = {1, -1, 0, 0};
        vector<int> dy = {0, 0, 1, -1};
        int round = 0;
        while(!q.empty()) {
            int qSize = q.size();
            round++;
            for (int i = 0; i < qSize; ++i) {
                pair<int, int> frontNode = q.front();
                q.pop();
                for (int j = 0; j < 4; ++j) {
                    int newX = frontNode.first + dx[j];
                    int newY = frontNode.second + dy[j];
                    if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == 0) {
                        q.push({newX, newY});
                        grid[newX][newY] = 1;
                    }
                }
            }
        }
        
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 0) return -1;
            }
        }
        
        return round - 1;
    }
};

代码同步在
https://github.com/luqian2017/Algorithm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值