Zombie in Matrix

来源:互联网 发布:公积金贷款的软件 编辑:程序博客网 时间:2024/06/05 00:30

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
原创粉丝点击