Walls and Gates

You are given a m x n 2D grid initialized with these three possible values.

-1 - A wall or an obstacle. 0 - A gate. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

BFS

Time Complexity
O(MN)
Space Complexity
O(N)

思路

Push all gates into queue first. Then for each gate update its neighbor cells and push them to the queue. For visited, I just check if the matrixi for 4 directions is bigger than the current matrixi, if it is bigger means it hasn't been visited.

代码

public void wallsAndGates(int[][] rooms) {
    //corner case
    if(rooms == null || rooms.length == 0 || rooms[0] == null || rooms[0].length == 0) return;
    Queue<int[]> queue = new LinkedList<int[]>();
    int step = 1;
    int rows = rooms.length, cols = rooms[0].length;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            if(rooms[i][j] == 0) queue.offer(new int[]{i, j});
        }
    }
    
    int[][] directions = new int[][]{{-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 : directions){
                int x = cur[0] + dir[0];
                int y = cur[1] + dir[1];
                if(x >= 0 && x < rows && y >= 0 && y < cols && rooms[x][y] > rooms[cur[0]][cur[1]]){
                    rooms[x][y] = step;
                    queue.offer(new int[]{x,y});
                }
            }
        }
        step++;
    }
}

annielulu
5 声望5 粉丝

引用和评论

0 条评论