Climbing Routes From the Corner: Batch Lookup of Shortest Paths
Trees & GraphsAuto-graded · 22 test casesLast updated
Run one BFS from the top-left cell of a grid with distinct values, using strictly increasing moves, then answer many target queries by rebuilding paths from stored parent links.
Climbing Routes From the Corner
You are given a rectangular grid of integers and a list of query values. For each query value, find a shortest route that starts at the top-left cell (0, 0) and ends at the cell holding that value, where every step goes to a strictly larger value.
From any cell you may step to its up, right, down, or left neighbor, as long as that neighbor lies inside the grid and holds a strictly greater value than the current cell.
Implement shortest_climbs(grid, queries). It returns one list per query, in the same order as queries. Each list contains the values along the chosen route, from the starting cell to the target cell, inclusive.
Rules
- The length of a route is the number of steps (edges). A route that consists only of the start cell has zero steps and is the list
[grid[0][0]]. - If the query value does not appear in the grid, or it appears but cannot be reached from the top-left cell by increasing moves, the answer for that query is an empty list
[]. - Several shortest routes may exist. Choose the one defined by this procedure: run a breadth-first search from
(0, 0)using a FIFO queue. When expanding a cell, examine its neighbors in the order up, right, down, left. Each cell is assigned to the first cell that discovers it, and that assignment is never changed. The route to a target is the chain of discoverers leading back to the start. - The grid never changes between queries, so do the traversal work once up front. Answering an individual query should only need a lookup plus building the output route, not a fresh search of the grid.
Constraints
- The grid has between 1 and 100 rows and between 1 and 100 columns, and it is rectangular.
- There are at most 1,000 queries.
- All grid values are distinct signed 32-bit integers, so each value identifies at most one cell.
- Query values are signed 32-bit integers and may repeat; each occurrence gets its own answer list.
Examples
Example 1
Input: shortest_climbs([[1, 2, 3], [4, 5, 8], [7, 9, 6]], [5, 6, 1])
Output: [[1, 2, 5], [], [1]]
Example 2
Input: shortest_climbs([[4, 3], [5, 6]], [6, 3, 9])
Output: [[4, 5, 6], [], []]
Hints
Hint 1
Only the destination changes between queries. Think about what can be computed once from the fixed start cell and shared by every query.
Hint 2
A breadth-first search on unit-cost moves finds shortest step counts. If you record, for each cell, which cell first discovered it, those links describe a route back to the start for every reachable cell.
Hint 3
Map each value to its cell with a dictionary. To answer a query, check that the cell was reached, follow the discoverer links back to the start, and reverse the collected values. Storing a full route per cell would take far more memory than one link per cell.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The start cell is fixed and only the target varies, so this is a single-source shortest-path problem answered many times. Every move costs one step, so one BFS from (0, 0) gives the shortest step count to every reachable cell.
During the BFS, record for each cell the cell that first discovered it (its predecessor). These links form a shortest-path tree rooted at the start.
To answer a query:
- Look up the target value in a
value -> (row, col)dictionary. Values are distinct, so the cell is unique. - If the value is missing, or its cell was never discovered by the BFS, answer
[]. - Otherwise follow predecessor links back to the start, collecting values, then reverse the list.
Why it is correct
- Shortest: a move only goes to a strictly larger value, so no cycles exist, and BFS on unit-cost edges discovers cells in non-decreasing order of distance. A cell's first discoverer lies one layer earlier, so walking back the predecessor chain gives exactly the minimum number of steps.
- Valid: a predecessor link is created only when the child's value is strictly greater than the parent's, so every step of the route is legal.
- Tie-break: the queue is FIFO, neighbors are scanned up, right, down, left, and a cell's predecessor is set once and never overwritten. That matches the required first-discovery rule.
- Start cell: its predecessor is
None, so queryinggrid[0][0]yields the one-element route. - Unreachable values: any value smaller than the start, or one walled in by smaller neighbors, is never discovered and gives
[].
Complexity
Let N = rows * cols and let L be the length of a returned route.
- Preprocessing: O(N) time and O(N) space (dictionary, predecessor map, queue).
- Per query: O(1) expected lookup plus O(L) to rebuild and reverse the route. O(L) is unavoidable since the output has L values.
- Total: O(N + Q + sum of L).
Storing a full route at every cell would cost up to Theta(N^2) memory in a snake-like maze, and queries would still need to copy the stored list. One predecessor per cell uses O(N) memory because routes share prefixes in the tree. Running a fresh BFS per query would cost O(Q * N) and repeat identical work.
Reference solution
from collections import deque
from typing import List
def shortest_climbs(grid: List[List[int]], queries: List[int]) -> List[List[int]]:
rows, cols = len(grid), len(grid[0])
cell_of = {grid[r][c]: (r, c) for r in range(rows) for c in range(cols)}
start = (0, 0)
came_from = {start: None}
queue = deque([start])
moves = ((-1, 0), (0, 1), (1, 0), (0, -1)) # up, right, down, left
while queue:
r, c = queue.popleft()
for dr, dc in moves:
nr, nc = r + dr, c + dc
if (0 <= nr < rows and 0 <= nc < cols
and grid[nr][nc] > grid[r][c]
and (nr, nc) not in came_from):
came_from[(nr, nc)] = (r, c)
queue.append((nr, nc))
answers = []
for value in queries:
pos = cell_of.get(value)
if pos is None or pos not in came_from:
answers.append([])
continue
route = []
cur = pos
while cur is not None:
route.append(grid[cur[0]][cur[1]])
cur = came_from[cur]
route.reverse()
answers.append(route)
return answers