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.
思路:
从每个点是1的点出发,通过bfs找到这个点到每个0点最短距离,同时记录该0点被1点访问过的次数。这样我们遍历所有1点,对所有能够被访问到的1点,保存最短距离以及增加访问次数。最后把所有0点遍历一遍,看它是否被所有1点访问到,并且最短距离和最小。
其实这里也可以从0出发,做类似的事情。选1还是0看它们的个数。谁小就选谁。
1 public class Solution { 2 private int[][] dir = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; 3 4 public int shortestDistance(int[][] grid) { 5 if (grid == null || grid.length == 0) { 6 return 0; 7 } 8 9 int rows = grid.length, cols = grid[0].length, numBuildings = 0; 10 int[][] reach = new int[rows][cols], distance = new int[rows][cols]; 11 12 // Find the minimum distance from all buildings 13 for (int i = 0; i < rows; i++) { 14 for (int j = 0; j < cols; j++) { 15 if (grid[i][j] == 1) { 16 shortestDistanceHelper(i, j, grid, reach, distance); 17 numBuildings++; 18 } 19 } 20 } 21 22 // step 2: check the min distance reachable by all buildings 23 int minDistance = Integer.MAX_VALUE; 24 for (int i = 0; i < rows; i++) { 25 for (int j = 0; j < cols; j++) { 26 if (grid[i][j] == 0 && reach[i][j] == numBuildings && distance[i][j] < minDistance) { 27 minDistance = distance[i][j]; 28 } 29 } 30 } 31 return minDistance == Integer.MAX_VALUE ? -1 : minDistance; 32 } 33 34 private void shortestDistanceHelper(int row, int col, int[][] grid, int[][] reach, int[][] distance) { 35 int rows = grid.length, cols = grid[0].length, d = 0; 36 boolean[][] visited = new boolean[rows][cols]; 37 Queue<int[]> queue = new LinkedList<>(); 38 queue.offer(new int[] { row, col }); 39 visited[row][col] = true; 40 while (!queue.isEmpty()) { 41 d++; 42 int size = queue.size(); 43 for (int j = 0; j < size; j++) { 44 int[] cord = queue.poll(); 45 for (int i = 0; i < 4; i++) { 46 int rr = dir[i][0] + cord[0]; 47 int cc = dir[i][1] + cord[1]; 48 if (isValid(rr, cc, grid, visited)) { 49 queue.offer(new int[] { rr, cc }); 50 visited[rr][cc] = true; 51 reach[rr][cc]++; 52 distance[rr][cc] += d; 53 } 54 } 55 } 56 } 57 } 58 59 private boolean isValid(int row, int col, int[][] grid, boolean[][] visited) { 60 int rows = grid.length, cols = grid[0].length; 61 if (row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || grid[row][col] == 2) { 62 return false; 63 } 64 return true; 65 } 66 }