public int shortestDistance(int[][] grid) {
if (grid == null || grid.length == 0) {
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int[][] distance = new int[m][n];
int[][] reach = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
getDistanceByBFS(i, j, distance, reach, directions, grid);
int res = Integer.MAX_VALUE;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0 && reach[i][j] == buildings) {
res = Math.min(res, distance[i][j]);
return res == Integer.MAX_VALUE ? -1 : res;
public void getDistanceByBFS(int row, int col, int[][] distance, int[][] reach, int[][] directions, int[][] grid) {
boolean[][] visited = new boolean[m][n];
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] {row, col});
while (!queue.isEmpty()) {
for (int i = 0; i < size; i++) {
int[] curCell = queue.remove();
for (int[] direction : directions) {
int nextRow = curCell[0] + direction[0];
int nextCol = curCell[1] + direction[1];
if (isValid(nextRow, nextCol, visited, grid)) {
distance[nextRow][nextCol] += dist;
reach[nextRow][nextCol] += 1;
queue.add(new int[] {nextRow, nextCol});
visited[nextRow][nextCol] = true;
public boolean isValid(int row, int col, boolean[][] visited, int[][] grid) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && !visited[row][col] && grid[row][col] == 0;