Approach
Breadth-first search
For Shortest Distance from All Buildings, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 72 lines of Java from the credited upstream file 317.java.
- The implementation visibly relies on sequence storage, work queue.
- 9 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int shortestDistance(int[][] grid) {3 final int m = grid.length;4 final int n = grid[0].length;5 final int nBuildings = getBuildingsCount(grid);6 int ans = Integer.MAX_VALUE;7 8 9 int[][] dist = new int[m][n];10 11 int[][] reachCount = new int[m][n];12 13 for (int i = 0; i < m; ++i)14 for (int j = 0; j < n; ++j)15 if (grid[i][j] == 1) 16 if (!bfs(grid, i, j, dist, reachCount, nBuildings))17 return -1;18 19 for (int i = 0; i < m; ++i)20 for (int j = 0; j < n; ++j)21 if (reachCount[i][j] == nBuildings)22 ans = Math.min(ans, dist[i][j]);23 24 return ans == Integer.MAX_VALUE ? -1 : ans;25 }26 27 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};28 29 private boolean bfs(int[][] grid, int row, int col, int[][] dist, int[][] reachCount,30 int nBuildings) {31 final int m = grid.length;32 final int n = grid[0].length;33 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(row, col)));34 boolean[][] seen = new boolean[m][n];35 seen[row][col] = true;36 int seenBuildings = 1;37 38 for (int step = 1; !q.isEmpty(); ++step)39 for (int sz = q.size(); sz > 0; --sz) {40 final int i = q.peek().getKey();41 final int j = q.poll().getValue();42 for (int[] dir : DIRS) {43 final int x = i + dir[0];44 final int y = j + dir[1];45 if (x < 0 || x == m || y < 0 || y == n)46 continue;47 if (seen[x][y])48 continue;49 seen[x][y] = true;50 if (grid[x][y] == 0) {51 dist[x][y] += step;52 ++reachCount[x][y];53 q.offer(new Pair<>(x, y));54 } else if (grid[x][y] == 1) {55 ++seenBuildings;56 }57 }58 }59 60 return seenBuildings == nBuildings;61 }62 63 private int getBuildingsCount(int[][] grid) {64 int buildingCount = 0;65 for (int[] row : grid)66 for (final int cell : row)67 if (cell == 1)68 ++buildingCount;69 return buildingCount;70 }71}72