Nearest Depot and Peak-Load Routing on a Grid
Trees & GraphsModel answerLast updated
Given a grid with depot cells, find shortest paths from query locations to any depot, then extend to pick the depot maximizing a distance-penalized load score.
Nearest Depot and Peak-Load Routing
You are working with a warehouse routing system modeled as an m × n grid of characters:
'W'— a warehouse depot'#'— an impassable wall' '(space) — an open passable cell
Movement is strictly four-directional (up, down, left, right). You cannot move outside the grid or into a '#' cell. Depots ('W') are passable — a path may continue through one.
You are given a list of K query locations, each as a (row, col) pair.
Part A
Implement nearestDepotDistances(grid, queries).
For each query location, return the minimum number of steps to reach any depot. Follow these rules:
- If the query cell itself is a depot, the distance is
0. - If the query cell is a wall (
'#') or there is no path to any depot, return-1.
Part B (follow-up)
Each depot at coordinates (r, c) has a non-negative integer base load L[r][c]. You are also given a non-negative integer beta.
Define the effective load of a depot at grid distance d from a query location as:
effective_load = max(0, L[r][c] - beta * d)
Implement peakLoadAssignments(grid, L, beta, queries).
For each query location, among all reachable depots, return the one that maximizes effective load. Break ties in this order:
- Smaller grid distance
d - Smaller row index
- Smaller column index
Return both the chosen depot's coordinates (row, col) and its effective load value for that query. If no depot is reachable (or the query cell is a wall or out of bounds), return ((-1, -1), -1).
Constraints
1 ≤ m, n ≤ 5001 ≤ K ≤ 10^50 ≤ L[r][c] ≤ 10^6for all depot cells0 ≤ beta ≤ 10^6- The grid contains at least one
'W'cell (though it may be unreachable from some queries)
What is expected
- A correct, well-structured implementation of both parts
- Clear explanation of your algorithmic approach and why you chose it
- Time and space complexity analysis
- Discussion of edge cases and how your code handles them
Hints
Hint 1
For Part A, think about what happens if you flip the search direction: instead of running BFS from every query toward the depots, start BFS simultaneously from all depots outward. What does the first-arrival distance at any cell represent?
Hint 2
For Part B, you need each cell to track not just a distance but which depot 'wins' it. Try encoding the tie-break priority into a single comparable key that you attach to each depot source, then think about which shortest-path algorithm preserves that key correctly as it propagates across edges.
Hint 3
Watch out for the clamping rule max(0, ...). When beta is large, many depots end up with effective load 0. In that scenario, which depot should win? Work through a small example where every depot's score clamps to zero and make sure your code produces the right answer rather than returning -1.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part A: multi-source BFS
The naive approach — one BFS per query — costs O(K · mn). With K up to 10^5 and a 500 × 500 grid, that is 25 billion cell visits in the worst case: far too slow.
The key insight is to reverse the search. Add every depot to a BFS queue at distance 0 and expand outward in a single pass. Because BFS visits cells in non-decreasing distance order, the first time it reaches any cell it has found the shortest distance from that cell to the nearest depot. After one O(mn) pass, every query is an O(1) lookup.
This is equivalent to adding a virtual super-source with a zero-cost edge to every depot and running one BFS from that super-source. Walls are never enqueued and stay at -1, as do cells that are completely walled off.
Part B: multi-source Dijkstra with labeled sources
Each cell now needs to know not just a distance but which depot wins it. The winning depot is the one minimizing:
key = (beta * d - L[src], d, src_row, src_col)
Minimizing this key is equivalent to maximizing effective load L - beta * d, with ties broken by smaller d, then row, then column. Notice that as a label travels one grid step, d increases by 1 and the first key component increases by beta. Keys strictly increase along edges (since beta ≥ 0 and we add at least 1 to d on a tie). This means Dijkstra's greedy argument holds: the first time a cell is popped from the min-heap, it has its globally optimal label. Each cell is settled exactly once.
Handling the clamp. max(0, ...) collapses all non-positive scores to 0. If the winning raw score is positive, that depot is the answer. If every reachable depot yields a non-positive raw score, all tie at effective load 0 and the tie-break reduces to nearest depot, then row, then column. That is exactly the result of running the same Dijkstra with L ≡ 0 and beta = 0. So the solution runs two passes and picks between them based on the sign of the raw score.
Complexity
| Part | Time | Space |
|---|---|---|
| A | O(mn + K) | O(mn) |
| B | O(mn log(mn) + K) | O(mn) |
Naive one-BFS-per-query is O(K · mn). One-BFS-per-depot is O(#W · mn). Both are worth mentioning to show you considered them before choosing the reversed multi-source approach.
Edge cases
- Wall or out-of-bounds query: return -1 /
((-1,-1), -1)immediately. - Query on a depot: distance 0 in Part A. In Part B a different depot can still win if its load is high enough — do not short-circuit.
- No reachable depot: all queries in a walled-off region stay at -1.
- beta = 0: effective load equals base load regardless of distance, so the highest-load depot always wins.
- All scores clamp to 0: the fallback nearest-depot pass handles this. Many candidates miss this case and either return -1 or the wrong depot.
- Paths through other depots:
'W'cells are passable; the BFS/Dijkstra must treat them like open cells when expanding neighbors. - Empty grid or no depots: return -1 for all queries.
Python implementation
from collections import deque
import heapq
from typing import Callable, List, Optional, Sequence, Tuple
DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1))
QueryList = List[Tuple[int, int]]
def nearestDepotDistances(
grid: Sequence[Sequence[str]],
queries: QueryList,
) -> List[int]:
"""Part A: steps to nearest depot, or -1 if unreachable/wall/oob."""
m = len(grid)
n = len(grid[0]) if m else 0
dist = [[-1] * n for _ in range(m)]
q: deque = deque()
for r in range(m):
for c in range(n):
if grid[r][c] == 'W':
dist[r][c] = 0
q.append((r, c))
while q:
r, c = q.popleft()
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] != '#' and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
q.append((nr, nc))
return [
dist[r][c] if (0 <= r < m and 0 <= c < n and grid[r][c] != '#') else -1
for r, c in queries
]
def _dijkstra_labels(
grid: Sequence[Sequence[str]],
base_score: Callable[[int, int], int],
penalty: int,
) -> List[List[Optional[Tuple]]]:
"""
Propagate depot labels across the grid.
Each cell receives the label (key0, d, src_r, src_c) from the depot
that minimizes key = (penalty*d - base_score, d, src_r, src_c).
Returns a 2D array of labels (None if cell is unreachable or a wall).
"""
m = len(grid)
n = len(grid[0]) if m else 0
label: List[List[Optional[Tuple]]] = [[None] * n for _ in range(m)]
heap: List[Tuple] = []
for r in range(m):
for c in range(n):
if grid[r][c] == 'W':
k0 = -base_score(r, c) # penalty*0 - score = -score at d=0
heapq.heappush(heap, (k0, 0, r, c, r, c))
while heap:
k0, d, sr, sc, r, c = heapq.heappop(heap)
if label[r][c] is not None:
continue
label[r][c] = (k0, d, sr, sc)
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] != '#' and label[nr][nc] is None:
# Moving one step: d increases by 1, key increases by penalty
heapq.heappush(heap, (k0 + penalty, d + 1, sr, sc, nr, nc))
return label
def peakLoadAssignments(
grid: Sequence[Sequence[str]],
L: List[List[int]],
beta: int,
queries: QueryList,
) -> List[Tuple[Tuple[int, int], int]]:
"""Part B: for each query, return (depot_coords, effective_load)."""
m = len(grid)
n = len(grid[0]) if m else 0
# Pass 1: optimize for max load (with beta penalty)
best = _dijkstra_labels(grid, lambda r, c: L[r][c], beta)
# Pass 2: optimize for nearest only (handles all-zero-clamp fallback)
near = _dijkstra_labels(grid, lambda r, c: 0, 0)
results = []
for r, c in queries:
if not (0 <= r < m and 0 <= c < n) or grid[r][c] == '#' or best[r][c] is None:
results.append(((-1, -1), -1))
continue
k0, d, sr, sc = best[r][c]
raw = L[sr][sc] - beta * d # may be negative before clamping
if raw > 0:
results.append(((sr, sc), raw))
else:
# Every depot clamps to 0; fall back to nearest-first tie-break
_, _, nr, nc = near[r][c] # type: ignore[misc]
results.append(((nr, nc), 0))
return results
Common mistakes
- Running BFS from each query separately instead of reversing the search — correct but too slow.
- Treating depot cells as walls during BFS expansion, which blocks paths that pass through depots.
- Forgetting to handle the all-clamp-to-zero case; returning the max-raw-score depot even when its effective value is negative.
- Using a plain BFS for Part B (which finds shortest distances but not winning labels) rather than Dijkstra.
- Encoding the tie-break key incorrectly, e.g. not including
(d, src_row, src_col)as secondary components, leading to wrong depot selection on ties.