public int shortestDistance(int[][] grid) {
        if (grid == null) return -1;

        int m = grid.length, n = grid[0].length;
        int buildingCnt = 0;
        int[][] dist = new int[m][n];
        int[][] nums = new int[m][n];

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) {
                    ++buildingCnt;
                    bfs(grid, dist, nums, i * n + j);
                }
            }
        }

        int minDist = Integer.MAX_VALUE;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 0 && nums[i][j] == buildingCnt) minDist = Math.min(minDist, dist[i][j]);
            }
        }
        return minDist == Integer.MAX_VALUE ? -1 : minDist;
    }