November 27, 2019

286. Walls and Gates

286. Walls and Gates

BFS. Time = O(mn), Space = O(mn) (queue’s size: insert most m*n points into the queue)

class Solution {
    public void wallsAndGates(int[][] rooms) {
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < rooms.length; i++) {
            for (int j = 0; j < rooms[0].length; j++) {
                if (rooms[i][j] == 0) {
                    queue.offer(new int[] {i, j});
                }
            }
        }
        int distance = 1;
        int[][] dirs = `{`{-1, 0}, {1, 0}, {0, -1}, {0, 1}`}`;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] cur = queue.poll();
                for (int[] dir : dirs) {
                    int row = cur[0] + dir[0];
                    int col = cur[1] + dir[1];
                    if (row < 0 || row > rooms.length - 1 || col < 0 || col > rooms[0].length - 1 || rooms[row][col] == -1 || rooms[row][col] <= distance) {
                        continue;
                    }
                    rooms[row][col] = distance;
                    queue.offer(new int[]{row, col});
                }
            }
            distance ++;
        }
    }
}
comments powered by Disqus