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.

class Coordinate {
    int x;
    int y;
    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
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;
        int people = 0;
        Queue<Coordinate> queue = new LinkedList<>();
        int[] directionX = {0, 0, 1, -1};
        int[] directionY = {1, -1, 0, 0};
        //找到所有僵尸,统计所有人数
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1) {
                    queue.offer(new Coordinate(i, j));
                }
                if (grid[i][j] == 0) {
                    people++;
                }
            }
        }
        if (people == 0) {
            return 0;
        }
        int time = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            time++;
            //System.out.println("当前是第" + time + "天,还剩" + people + "人");
            for (int i = 0; i < size; i++) {
                //分层遍历,增加一层for循环,在for循环里再进行poll()!!!
                Coordinate coor = queue.poll();
                for (int j = 0; j < 4; j++) {
                    Coordinate adj = new Coordinate(
                        coor.x + directionX[j],
                        coor.y + directionY[j]
                    );
                    if (inBound(adj, grid)) {
                        if (grid[adj.x][adj.y] == 0) {
                            grid[adj.x][adj.y] = 1;
                            people--;
                            if (people == 0) {
                                return time;
                            }
                            queue.offer(adj);
                        }
                    }
                }
            }
        }
        return -1;
    }
    private boolean inBound(Coordinate coor, int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int x = coor.x;
        int y = coor.y;
        return x >= 0 && x < n && y >= 0 && y < m && grid[x][y] != 2;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值