Zombie in Matrix

http://lintcode.com/en/problem/zombie-in-matrix/

when people is equal to 0, then you should return result. Not until the queue id empty(the end of the bfs traverse completely)!!

public class Solution {
    /*
     * @param grid: a 2D integer grid
     * @return: an integer
     */
    private static int n, m; 
    int[] dx = {1, 0, 0, -1};
    int[] dy = {0, 1, -1, 0};

    public int zombie(int[][] grid) {
        // write your code here
        Queue<Integer> xq = new LinkedList<>();
        Queue<Integer> yq = new LinkedList<>();

        n = grid.length;
        m = grid[0].length;
        int people = 0;

        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(grid[i][j] == 1){
                    xq.offer(i);
                    yq.offer(j);
                }

                if(grid[i][j] == 0){
                    people++;
                }
            }
        }

        int num = 0;

        if (people == 0) {
            return 0;
        }

        while(!xq.isEmpty()){
            int size = xq.size();

            num++;
            for(int i = 0; i < size; i++){
                int cx = xq.poll();
                int cy = yq.poll();

                for(int j = 0; j < 4; j++){
                    int nx = cx + dx[j];
                    int ny = cy + dy[j];

                    if(inbound(nx, ny) && grid[nx][ny] == 0){
                        people--;
                        if(people == 0){
                            return num;
                        }
                        grid[nx][ny] = 1;
                        xq.offer(nx);
                        yq.offer(ny);
                    }
                }
            }

            // printGrid(grid);
        }

        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(grid[i][j] == 0){
                    return -1;
                }
            }
        }

        return num;
    }

    private boolean inbound(int x, int y){
        if(x < 0 || y < 0 || x >= n || y >= m){
            return false;
        }

        return true;
    }

    void printGrid(int[][] grid){
        List<List<Integer>> lists = new ArrayList<>();
        for(int i = 0; i < n; i++){
            lists.add(new ArrayList<>());
            for(int j = 0; j < m; j++){
                lists.get(i).add(grid[i][j]);                
            }
        }

        System.out.println(lists);
    }
}

results matching ""

    No results matching ""