KatInterview

Cheapest Transit Pick on a Lettered Street Grid

Trees & GraphsAuto-graded · 25 test cases
MediumAuto-gradedTrees & Graphsbfsgridshortest-path

Last 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 digit m or 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 m adds time[m - 1] to the total time and cost[m - 1] to the total cost. A journey of s steps therefore takes s * time[m - 1] time and costs s * 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 -1 if no option can reach 'D'.

Constraints

  • 1 <= len(grid) <= 500 and 1 <= 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, and 1 <= 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.