Zombie in Matrix Lintcode

Given a 2D grid, each cell is either a wall 2, a zombie 1or 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

In this question, I store i * m + j in the queue, and m is the column number in the matrix.
 
In this question, pay attention that I should count the day first, becasue in the last day, everyone is zombie but if I don't return the day, the queue will keep iterate because it is not empty. For example, if I return the day number in the first day, the day should be 1. So add the day at first.
 
And pay attention that I can count the people first so if it drop to 0 I can return directly.
 
public class Solution {
    /**
     * @param grid  a 2D integer grid
     * @return an integer
     */
    public int zombie(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }
        int n = grid.length;
        int m = grid[0].length;
        Queue<Integer> q = new LinkedList<>();
        
        int people = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    q.offer(i * m + j);
                }
                if (grid[i][j] == 0) {
                    people++;
                }
            }
        }
        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};
        
        int day = 0;

        while (!q.isEmpty()) {
            day++;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                int point = q.poll();

                int x = point / m;
                int y = point % m;
                for (int j = 0; j < 4; j++) {
                    int nx = x + dx[j];
                    int ny = y + dy[j];
                    if (isValid(grid, nx, ny) && grid[nx][ny] == 0) {
                        q.offer(nx * m + ny);
                        grid[nx][ny] = 1;
                        people--;
                        if (people == 0) {
                            return day;
                        }
                    }
                }
            }
        }
        return -1;
    }
    private boolean isValid(int[][] grid, int x, int y) {
        return x >= 0 && y >= 0 && x < grid.length && y < grid[0].length;
    }
}

 

 

转载于:https://www.cnblogs.com/aprilyang/p/6505178.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值