Shortest Grid Path to Nearest Fulfillment Hub
Trees & GraphsAuto-graded · 22 test casesLast updated
Find the minimum travel distance from every destination point to its closest source hub on a 2D grid using multi-source Breadth-First Search.
You are given a 2D grid represented as a list of strings, where each character denotes a cell type:
'S': A fulfillment store (source)'H': A customer residence (destination)'.': An open, traversable path'#': An impassable barrier
Movement is permitted only in the four cardinal directions (up, down, left, right) across non-barrier cells ('S', 'H', and '.'). You can freely step onto or pass through other stores or residences.
For each residence ('H'), compute the shortest path distance (measured in number of steps) to the nearest fulfillment store ('S'). If a residence cannot be reached from any store, its distance is defined as -1.
Return a list of integers containing the minimum distance for each residence, ordered by the appearance of each 'H' in standard row-major order (scanning top to bottom, left to right).
Constraints
- $0 \le \text{len(grid)} \le 500$
- $0 \le \text{len(grid[r])} \le 500$ for all $r$
- All strings in
gridhave the same length. - The grid contains only the characters
'S','H','.'), and'#'.
Examples
Example 1
Input: grid_delivery_distances(['S..', '...', '..H'])
Output: [4]
Example 2
Input: grid_delivery_distances(['S#H', '...', 'H..'])
Output: [4, 2]
Example 3
Input: grid_delivery_distances(['H.H', '###', 'S..'])
Output: [-1, -1]
Example 4
Input: grid_delivery_distances(['...', '...'])
Output: []
Hints
Hint 1
Running an independent BFS from each residence can be too slow if there are many residences.
Hint 2
Consider reversing the search direction or starting BFS from all stores simultaneously.
Hint 3
Using a multi-source BFS allows you to compute the minimum distance from any store to every cell in a single pass of time O(rows * cols).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Multi-Source Breadth-First Search (BFS)
A single-source BFS from each residence 'H' would take $O(H \cdot R \cdot C)$ time, where $R$ and $C$ are the grid dimensions and $H$ is the number of residences. In the worst case, this degrades to $O((R \cdot C)^2)$, which is inefficient for larger grids.
Because edge weights are uniform (each step costs 1 unit) and distance is symmetric, we can flip the problem: compute the shortest path from all stores ('S') to every grid cell simultaneously.
-
Initialization:
- Scan the grid in row-major order to identify all store coordinates (
'S') and residence coordinates ('H'). - Create a 2D distance matrix initialized to
-1. - Push all store cells into a single BFS double-ended queue with distance
0.
- Scan the grid in row-major order to identify all store coordinates (
-
Traversal:
- Pop coordinates $(r, c)$ from the front of the queue.
- For each valid neighboring cell $(nr, nc)$ in the 4 cardinal directions that is not an obstacle (
'#') and has not yet been visited (distance == -1):- Set
distance[nr][nc] = distance[r][c] + 1. - Push $(nr, nc)$ into the queue.
- Set
-
Result Extraction:
- Map each recorded residence coordinate to its computed distance from the distance matrix.
Why it is correct
BFS visits cells in non-decreasing order of distance. By seeding the queue with all store locations at level 0, every cell is discovered via its shortest path from whichever store reaches it first. The first time a cell is reached, its assigned distance is guaranteed to be optimal. Unreachable residences retain their initial value of -1.
Complexity Analysis
- Time Complexity: $\mathcal{O}(R \cdot C)$, as each cell is enqueued and processed at most once, performing $\mathcal{O}(1)$ neighbor checks.
- Space Complexity: $\mathcal{O}(R \cdot C)$ to store the distance matrix and the BFS queue.
from collections import deque
from typing import List
def grid_delivery_distances(grid: List[str]) -> List[int]:
if not grid or not grid[0]:
return []
rows = len(grid)
cols = len(grid[0])
distances = [[-1] * cols for _ in range(rows)]
queue = deque()
homes = []
for r in range(rows):
for c in range(cols):
if grid[r][c] == 'S':
distances[r][c] = 0
queue.append((r, c))
elif grid[r][c] == 'H':
homes.append((r, c))
while queue:
r, c = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
if grid[nr][nc] != '#' and distances[nr][nc] == -1:
distances[nr][nc] = distances[r][c] + 1
queue.append((nr, nc))
return [distances[r][c] for r, c in homes]