Problem solution · Python

Shortest Distance from All Buildings

Shortest Distance from All Buildings: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
54 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 54 lines of Python from the credited upstream file 317.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeShortest Distance from All Buildings · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def shortestDistance(self, grid: list[list[int]]) -> int:    DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))    m = len(grid)    n = len(grid[0])    nBuildings = sum(a == 1 for row in grid for a in row)    ans = math.inf    # dist[i][j] := the total distance of grid[i][j] (0) to reach all the    # buildings (1)    dist = [[0] * n for _ in range(m)]    # reachCount[i][j] := the number of buildings (1) grid[i][j] (0) can reach    reachCount = [[0] * n for _ in range(m)]     def bfs(row: int, col: int) -> bool:      q = collections.deque([(row, col)])      seen = {(row, col)}      seenBuildings = 1       step = 1      while q:        for _ in range(len(q)):          i, j = q.popleft()          for dx, dy in DIRS:            x = i + dx            y = j + dy            if x < 0 or x == m or y < 0 or y == n:              continue            if (x, y) in seen:              continue            seen.add((x, y))            if not grid[x][y]:              dist[x][y] += step              reachCount[x][y] += 1              q.append((x, y))            elif grid[x][y] == 1:              seenBuildings += 1        step += 1       # True if all the buildings (1) are connected      return seenBuildings == nBuildings     for i in range(m):      for j in range(n):        if grid[i][j] == 1:  # BFS from this building.          if not bfs(i, j):            return -1     for i in range(m):      for j in range(n):        if reachCount[i][j] == nBuildings:          ans = min(ans, dist[i][j])     return -1 if ans == math.inf else ans 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗