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:segmentfault
Each 0 marks an empty land which you can pass by freely.ide
Each 1 marks a building which you cannot pass through.ui
Each 2 marks an obstacle which you cannot pass through.idea
For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):spa
1 - 0 - 2 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0The 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.code
Note:
There will be at least one building. If it is not possible to build such house according to the above rules, return -1.three
這道理相似於Walls ang Gates, 解決方法也應該是從building出發進行BFS,不過這裏不一樣的是這裏須要返回最小距離和,因此咱們應該一個一個的對building的點BFS,用一個二維矩陣存每一個點到全部building的距離和,每次BFS,都更新相應的距離和。最後遍歷那個距離和矩陣,找出最小值便可。rem
須要注意的是,這道題還有個條件就是empty room 必須 reach all buildings,因此咱們能夠用另一個矩陣存對應empty room到building的個數,若是最終個數不等於總的building數,對應點存的距離和無效。get
time: O(kMN), space: O(MN), k表示building數量it
public class Solution { public int shortestDistance(int[][] grid) { int rows = grid.length; if (rows == 0) { return -1; } int cols = grid[0].length; // 記錄到各個building距離和 int[][] dist = new int[rows][cols]; // 記錄到能到達的building的數量 int[][] nums = new int[rows][cols]; int buildingNum = 0; // 從每一個building開始BFS for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == 1) { buildingNum++; bfs(grid, i, j, dist, nums); } } } int min = Integer.MAX_VALUE; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == 0 && dist[i][j] != 0 && nums[i][j] == buildingNum) min = Math.min(min, dist[i][j]); } } if (min < Integer.MAX_VALUE) return min; return -1; } public void bfs(int[][] grid, int row, int col, int[][] dist, int[][] nums) { int rows = grid.length; int cols = grid[0].length; Queue<int[]> q = new LinkedList<>(); q.add(new int[]{row, col}); int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // 記錄訪問過的點 boolean[][] visited = new boolean[rows][cols]; int level = 0; while (!q.isEmpty()) { level++; int size = q.size(); for (int i = 0; i < size; i++) { int[] coords = q.remove(); for (int k = 0; k < dirs.length; k++) { int x = coords[0] + dirs[k][0]; int y = coords[1] + dirs[k][1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !visited[x][y] && grid[x][y] == 0) { visited[x][y] = true; dist[x][y] += level; nums[x][y]++; q.add(new int[]{x, y}); } } } } } }