Shortest Path from Multiple Sources in a Grid
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests understanding of multi-source BFS to efficiently compute shortest distances from any of several starting points to many query locations.
You're working with a rectangular grid represented as a 2D array with m rows and n columns. Each cell contains one of three values:
0indicates a source location-1indicates an obstacle (cannot be traversed)2147483647(2³¹ - 1) indicates an open space
Movement between cells is restricted to four directions (up, down, left, right), and each move has a cost of 1.
Given a list of query coordinates, where each query is a pair [row, col] representing an open space in the grid, determine the length of the shortest path from each query location to any source. If a query location cannot reach any source, return -1 for that query.
Implement a function that returns an array of integers, one for each query in the same order as the input queries.
Constraints:
0 ≤ m, n ≤ 10000 ≤ k ≤ 100000(number of queries)- All query coordinates are guaranteed to be valid indices within the grid
- All query coordinates point to open spaces (cells with value
2147483647) - Grid cells contain only the three specified values:
0,-1, or2147483647
Examples
Example 1
Input: shortest_source_distances([[0, 2147483647, 2147483647], [-1, 2147483647, 0], [2147483647, 2147483647, -1]], [[0, 1], [0, 2], [1, 1], [2, 0]])
Output: [1, 1, 1, 3]
Example 2
Input: shortest_source_distances([[-1, 2147483647], [-1, 2147483647]], [[0, 1], [1, 1]])
Output: [-1, -1]
Example 3
Input: shortest_source_distances([[0, 2147483647, 2147483647], [2147483647, -1, 2147483647]], [[0, 1], [0, 2], [1, 0], [1, 2]])
Output: [1, 2, 1, 3]
Example 4
Input: shortest_source_distances([[0, 2147483647, -1, 2147483647], [2147483647, 2147483647, -1, 2147483647], [-1, -1, -1, 2147483647], [2147483647, 2147483647, 2147483647, 0]], [[0, 1], [1, 0], [1, 1], [3, 2]])
Output: [1, 1, 2, 1]
Hints
Hint 1
Instead of searching from each query toward sources, consider searching from sources toward all reachable cells.
Hint 2
Multi-source BFS can process all sources simultaneously by initializing the queue with all source locations at distance 0.
Hint 3
Precomputing distances to all cells allows you to answer each query in constant time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to reverse the search direction. Rather than performing a separate breadth-first search from each query location toward the sources (which would be inefficient for many queries), we perform a single multi-source BFS starting from all sources simultaneously.
Algorithm:
- Initialize a distance tracking matrix where each cell starts as unvisited (
-1), obstacles are marked (-2), and sources start at distance0 - Add all source locations to a BFS queue with initial distance
0 - Process the queue in breadth-first order: for each cell at distance
d, mark all unvisited, non-obstacle neighbors with distanced + 1and add them to the queue - After BFS completes, each reachable cell contains its shortest distance to the nearest source
- Answer each query with a constant-time lookup in the distance matrix
Why this works:
Multi-source BFS is equivalent to single-source BFS from an imaginary node connected to all actual sources with zero-cost edges. BFS guarantees that cells are discovered in non-decreasing order of distance. The first time a cell is reached represents the shortest path from any source to that cell. Since we start with all sources at distance 0 and expand outward layer by layer, each cell gets labeled with its minimum distance to the closest source.
Cells that remain unvisited after BFS completes are unreachable from all sources, correctly returning -1.
Edge cases handled:
- Empty query list returns empty result
- Grid with no sources: queue starts empty, all queries return
-1 - Areas blocked by obstacles: BFS never crosses obstacles, isolated regions stay unreachable
- Duplicate queries: each lookup is independent and efficient
Complexity:
- Time: O(m × n + k) where m×n is the grid size and k is the number of queries. The BFS visits each cell at most once (checking 4 neighbors per cell), and each query is answered in O(1)
- Space: O(m × n) for the distance matrix and BFS queue
This is dramatically more efficient than running k separate BFS operations, which would be O(k × m × n).
from collections import deque
from typing import List
def shortest_source_distances(grid: List[List[int]], queries: List[List[int]]) -> List[int]:
if not queries:
return []
if not grid or not grid[0]:
return [-1] * len(queries)
rows = len(grid)
cols = len(grid[0])
distance = [[-1] * cols for _ in range(rows)]
queue = deque()
for r in range(rows):
for c in range(cols):
if grid[r][c] == -1:
distance[r][c] = -2
elif grid[r][c] == 0:
distance[r][c] = 0
queue.append((r, c))
while queue:
r, c = queue.popleft()
next_distance = distance[r][c] + 1
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 and distance[nr][nc] == -1:
distance[nr][nc] = next_distance
queue.append((nr, nc))
return [distance[r][c] if distance[r][c] >= 0 else -1 for r, c in queries]