Problem

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

思路

  1. zombie turns its nearest people into zombie every day. search zombie's next layer. after we turn all people in that layer, that day is done.
  2. use bfs to search all zombie's nearest people layer by layer.
    public int zombie(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }

        int r = grid.length;
        int c = grid[0].length;
        Queue<int[]> queue = new LinkedList<>();

        int people = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == 1) {
                    int[] cord = {i, j};
                    queue.offer(cord);
                } else if (grid[i][j] == 0) {
                    people++;
                }
            }
        }

        int[] deltaX = {1, -1, 0, 0};
        int[] deltaY = {0, 0, 1, -1};
        int days = 0;

        while (!queue.isEmpty()) {
            int size = queue.size();
            days++;
            for (int i = 0; i < size; i++) {
                int[] curt = queue.poll();
                for (int j = 0; j < 4; j++) {
                    int[] adj = {curt[0] + deltaX[j], curt[1] + deltaY[j]};
                    if (adj[0] < 0 || adj[1] < 0 || adj[0] >= r || adj[1] >= c || grid[adj[0]][adj[1]] != 0) continue;

                    queue.offer(adj);
                    grid[adj[0]][adj[1]] = 1;
                    people--;
                    if (people == 0) {
                        return days;
                    }
                }
            }

        }

        return -1;
    }

results matching ""

    No results matching ""