Shortest Distance from All Buildings
题目链接:https://leetcode.com/problems...
这道题要求最短的距离,一般这种要求可以到的地方的距离,都需要把整个图遍历一遍,遍历一般就是bfs和dfs。这道题不用dfs的原因是:empty的位置到building的距离是按最小值来算的,用dfs每次如果放入depth不一定是最小的距离,每次都得更新,没有效率。这道题用bfs的原因:一样的原因,因为距离就是按照最小的距离来算的,完全是bfs的思路。
visited一般两种方式:用一个boolean的矩阵,直接改写grid的值。这里用第二种。-grid[i] [j]表示(i, j)点可以reach到的building数目。当grid[i] [j] == # of buildings so far时,证明当前点还没被visited,且当前点被之前所有的buildings都visited过,那么每次bfs只访问这些点。如果该point没有被之前所有的buildings访问过,就不可能成为答案(根据要求empty的位置能到所有的buildings),其他与它相邻的点也是这样。和用boolean矩阵比,缩小了每次遍历的范围。
从每一个building,即grid[i] [j] == 1的点开始做bfs层次遍历。
用一个distance矩阵来记录(i, j)到所有building的距离和,对每一个building做bfs
-
每次bfs的时候,更新distance[i] [j]的值:
Queue<int[]> 记录point
更新level += 1
-
go over当前level的全部point
-
if (i, j)在图内&grid[i] [j] = -num:
distance[i] [j] += level
grid[i] [j] --
q.offer(i, j)
-
go over整个distance数组,当-grid[i] [j] == # of buildings时,更新最小的距离值
public class Solution {
public int shortestDistance(int[][] grid) {
/* approach: bfs, distance array
* for each building, do a bfs, add the distance
* variable: num: record number of buildings already searched
* visited => use the grid => do -- if visited[i][j] = -num
* result: the grid[i][j] == -(number of buildings) is the possible
* find the smallest distance[i][j]
*/
distance = new int[grid.length][grid[0].length];
int num = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == 1) {
bfs(grid, i, j, -num);
num++;
}
}
}
int result = Integer.MAX_VALUE;
// find the smallest distance
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(grid[i][j] == -num) result = Math.min(result, distance[i][j]);
}
}
return result == Integer.MAX_VALUE ? -1 : result;
}
int[][] distance;
int[] dx = new int[] {-1, 1, 0, 0};
int[] dy = new int[] {0, 0, -1, 1};
private void bfs(int[][] grid, int x, int y, int num) {
Queue<int[]> q = new LinkedList();
q.offer(new int[] {x, y});
int len = 0;
while(!q.isEmpty()) {
len++;
// current level
for(int j = q.size(); j > 0; j--) {
int[] cur = q.poll();
// 4 directions
for(int i = 0; i < 4; i++) {
int nx = cur[0] + dx[i], ny = cur[1] + dy[i];
if(nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == num) {
distance[nx][ny] += len;
q.offer(new int[] {nx, ny});
grid[nx][ny]--;
}
}
}
}
}
}