Cheapest Transit Pick on a Lettered Street Grid
Trees & GraphsAuto-graded · 25 test casesLast updated
Run a per-mode BFS on a grid to find step counts, then choose the mode with least total time, then least total cost, then smallest index.
You are given a town map as a rectangular grid of strings, one string per row. The grid contains exactly one 'S' (where you begin) and exactly one 'D' (where you want to end up). Every other cell is either a digit '1' to '4', meaning that cell is a road that only transport option with that number may use, or 'X', meaning the cell is impassable for everyone.
Each of the four transport options has a fixed duration per step and a fixed price per step, given by the lists time and cost (option m uses time[m - 1] and cost[m - 1]). A journey uses just one option from start to finish.
Pick the option whose journey from 'S' to 'D' has the smallest total time. If several options tie on total time, prefer the smaller total cost. If they still tie, prefer the smaller option number.
Movement rules
- Each step goes to one of the four edge-adjacent cells (up, down, left, right). No diagonal steps.
- With option
m(1 to 4), a step may enter a cell only if that cell holds the digitmor is'D'. The journey begins at'S'. Cells marked'X', cells showing another option's digit, and'S'itself may not be entered. - Every step with option
maddstime[m - 1]to the total time andcost[m - 1]to the total cost. A journey ofssteps therefore takess * time[m - 1]time and costss * cost[m - 1]. For each option, use the route with the fewest steps possible. - Return the option number (1 to 4) chosen by the rule above, or
-1if no option can reach'D'.
Constraints
1 <= len(grid) <= 500and1 <= len(grid[r]) <= 500; all rows have equal length.- Each character is one of
'S','D','X','1','2','3','4', with exactly one'S'and exactly one'D'. len(time) == len(cost) == 4, and1 <= time[i], cost[i] <= 10^4.- Totals can reach roughly
2.5 * 10^9, which is beyond 32-bit range (Python handles this natively).
Examples
Example 1
Input: pick_transit_option(['S11X', '2X1X', '2X11', '222D'], [3, 2, 1, 1], [1, 5, 1, 1])
Output: 2
Example 2
Input: pick_transit_option(['S11X', '2X1X', '2X11', '222D'], [2, 2, 5, 5], [1, 3, 1, 1])
Output: 1
Example 3
Input: pick_transit_option(['S1X', 'XXD'], [1, 1, 1, 1], [1, 1, 1, 1])
Output: -1
Hints
Hint 1
Within a single option every step costs the same amount of time and money, so the option's total time and total cost are both just the step count times a constant.
Hint 2
Because of that, for each option you only need the minimum number of steps from S to D, using only that option's cells (plus D). Breadth-first search finds this.
Hint 3
Compute the key (steps * time, steps * cost, option number) for every option that reaches D and take the smallest tuple; if none reach D, return -1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Inside one option, each step has the same time and the same cost. So that option's total time and total cost are both the step count multiplied by a constant. Minimizing time for an option is therefore the same as minimizing its number of steps, and there is no trade-off between time and cost within an option.
This gives a simple plan:
- For each option
mfrom 1 to 4, run a breadth-first search from'S'that may only enter cells labeledm, and treats'D'as a valid target. Record the fewest steps, or note that'D'is unreachable. - For every option that reaches
'D', form the key(steps * time[m-1], steps * cost[m-1], m). - Return the option from the smallest key (tuples compare lexicographically), or
-1if there is none.
Why it is correct
- For a fixed option, the allowed cells form an unweighted graph:
'S', the cells labeledm, and'D'. BFS visits nodes in nondecreasing distance, so the first time we see'D'next to a dequeued cell,dist + 1is the minimum step count. - Cells of other options,
'X'cells and'S'are never added to the queue ('S'is already visited and never equals a digit), so the movement rules are respected. - The tuple key expresses "least time, then least cost, then smallest number" exactly.
Complexity
- Time: O(R * C), since there are four BFS passes, each visiting every cell at most once.
- Space: O(R * C) for the padded grid, the distance map and the queue.
The grid is padded with a border of 'X' and flattened, so neighbors are found with x +/- 1 and x +/- W without bounds checks.
Reference solution
from collections import deque
def pick_transit_option(grid: list[str], time: list[int], cost: list[int]) -> int:
R = len(grid)
C = len(grid[0])
W = C + 2
flat = ["X"] * (W * (R + 2))
s = -1
for r in range(R):
row = grid[r]
base = (r + 1) * W + 1
for c in range(C):
ch = row[c]
flat[base + c] = ch
if ch == "S":
s = base + c
moves = (1, -1, W, -W)
def min_steps(mode_char):
dist = {s: 0}
q = deque([s])
while q:
x = q.popleft()
nd = dist[x] + 1
for mv in moves:
y = x + mv
ch = flat[y]
if ch == "D":
return nd
if ch == mode_char and y not in dist:
dist[y] = nd
q.append(y)
return -1
best = None
for m in range(1, 5):
steps = min_steps(str(m))
if steps < 0:
continue
key = (steps * time[m - 1], steps * cost[m - 1], m)
if best is None or key < best:
best = key
return -1 if best is None else best[2]