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 distancefor(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 levelfor(int j = q.size(); j > 0; j--) {int[] cur = q.poll();// 4 directionsfor(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]--;}}}}}
}