zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    rocketmq 命令示例
    原 荐 使用Spring Boot Actuator、Jolokia和Grafana实现准实时监控
    业务系统中最核心的状态设计,异常 case. (系统设计)
    大数据架构分析
    开源 java 电商系统
    数据一致性对账平台架构
    管理中遇到的问题--人,组织上的问题
    腾讯后台开发面试题
    理解inode
    TCP序列号和确认号
  • 原文地址:https://www.cnblogs.com/casperwin/p/7456306.html
Copyright © 2011-2022 走看看