Zombie in Matrix

来源:互联网 发布:linux查看端口被占用 编辑:程序博客网 时间:2024/06/06 04:00

description:
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.

Have you met this question in a real interview? Yes
Example
Given a matrix:

0 1 2 0 0
1 0 0 2 1
0 1 0 0 0
return 2

整体的解题思路还是使用bfs去处理,只是中间多了几个处理步骤而已。
没有bugfree,单词拼写是大问题。

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     */    int PEOPLE = 0;    int WALL = 2;    int ZOMBIE = 1;    public int zombie(int[][] grid) {        // Write your code here        if (grid == null || grid.length == 0 || grid[0].length == 0) {            return 0;        }        int row = grid.length;        int column = grid[0].length;        int people = 0;        int zombie = 0;        Queue<Coordinate> queue = new LinkedList<>();        for(int i = 0; i < row; i++) {            for(int j = 0; j < column; j++) {                if (grid[i][j] == PEOPLE) {                    people++;                }                if (grid[i][j] == ZOMBIE) {                    zombie++;                    queue.offer(new Coordinate(i, j));                }            }        }        if (people == 0) {            return 0;        }        // bfs        int[] directX = {0, 1, -1, 0};        int[] directY = {1, 0, 0, -1};        int day = 0;        while (!queue.isEmpty()) {            day++;            int size = queue.size();            for (int a = 0; a < size; a++) {                Coordinate node = queue.poll();                for (int i = 0; i < 4; i++) {                    Coordinate coor = new Coordinate(node.x + directX[i],                                                     node.y + directY[i]);                    if (!isPeople(grid, coor)) {                        continue;                    }                    if (grid[coor.x][coor.y] == PEOPLE) {                        grid[coor.x][coor.y] = ZOMBIE;                        people--;                    }                    if (people == 0) {                        return day;                    }                    queue.offer(coor);                }             }        }        return -1;    }    private boolean isPeople(int[][] grid, Coordinate coor) {        int row = grid.length;        int column = grid[0].length;        if (coor.x < 0 || coor.x >= row) {            return false;        }        if (coor.y < 0 || coor.y >= column) {            return false;        }        if (grid[coor.x][coor.y] != PEOPLE) {            return false;        }        return true;    }}
0 0
原创粉丝点击