317. Shortest Distance from All Buildings

You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
Each 0 marks an empty land which you can pass by freely.
Each 1 marks a building which you cannot pass through.
Each 2 marks an obstacle which you cannot pass through.

For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):
1 - 0 - 2 - 0 - 1
|   |   |   |   |
0 - 0 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 1 - 0 - 0
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.

Note:
There will be at least one building. If it is not possible to build such house according to the above rules, return -1.

Solution:BFS 染色

思路:
Time Complexity: O(#buildings(mn)) Space Complexity: O(mm)
The time complexity for BFS/DFS is O(|V|+|E|).
In this problem, every vertex has up to 4 edges (left, right, up, down), so |E| ~ 4|V|. Thus, you have overall O(|V|) = O(mn) for a BFS.
This has been proven for all sparse graphs like this problem. Now, we do a BFS for each building, so the overall complexity is O(#buildings
(mn)). In worst case, every vertex is a building. So the number of buildings is also upper bounded by O(mn), and thus you have O((mn)(mn)) = O(m2n2). This is a very loose bound since when every vertex is a building, we don't even need to do a BFS (nowhere to go).

Solution Code:

class Solution {
    public int shortestDistance(int[][] grid) {
        if(grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }
        int m = grid.length;
        int n = grid[0].length;
        
        int[][] distance = new int[m][n];
        int[][] reach = new int[m][n];
        
        int building_num = 0;
        final int[] shift = new int[] {0, -1, 0, 1, 0};
        for(int row  = 0; row < m; row++) {
            for(int col = 0; col < n; col++) {
                
                if(grid[row][col] == 1) {
                    building_num++;
                    
                   // bfs
                    Queue queue = new LinkedList<>();
                    boolean[][] visited = new boolean[m][n];

                    int level = 0;
                    queue.offer(new int[]{row, col});
                    visited[row][col] = true;
                    while(!queue.isEmpty()) {
                        int q_size = queue.size();
                        for(int q = 0; q < q_size; q++) {
                            int[] cur = queue.poll();
                            distance[cur[0]][cur[1]] += level;
                            reach[cur[0]][cur[1]]++;
                            for(int k = 0; k < 4; k++) {
                                int next_row = cur[0] + shift[k];
                                int next_col = cur[1] + shift[k + 1];
                                if(next_row >= 0 && next_row < m && next_col >= 0 && next_col < n && grid[next_row][next_col] == 0 && !visited[next_row][next_col]) {
                                    visited[next_row][next_col] = true;
                                    queue.offer(new int[] {next_row, next_col});
                                }
                            }

                        }
                        level++;
                    } 
                }
                
                
            }
        }
        
        int shortest = Integer.MAX_VALUE;
        for (int row = 0; row < m; row++) {
            for (int col = 0; col < n; col++) {
                if (grid[row][col] == 0 && reach[row][col] == building_num) {
                    shortest = Math.min(shortest, distance[row][col]);
                }
            }
        }
        
        return shortest == Integer.MAX_VALUE ? -1 : shortest;
        
    }
}

你可能感兴趣的:(317. Shortest Distance from All Buildings)