A city is modeled as an m x n grid. Each cell holds a transportation mode, written as one character, and each mode has a fixed travel time for entering that cell:
-
'W'
(Walk) costs
10
time units
-
'B'
(Bike) costs
5
time units
-
'C'
(Car) costs
2
time units
-
'T'
(Train) costs
1
time unit
You are given a start position [start_row, start_col] and an end position [end_row, end_col]. You can move up, down, left or right. Each move costs the travel time of the destination cell, the one you step into. Return the minimum total travel time to get from start to end. If start equals end, return 0.
Function Signature
def fastest_path(grid: list[list[str]], start: list[int], end: list[int]) -> int:
Rules
-
grid
is a list of rows, and each row is a list of one-character strings, each one of
'W'
,
'B'
,
'C'
,
'T'
.
-
start
and
end
are
[row, col]
pairs with 0-based indices.
-
The mode of the start cell is never charged. The mode of the end cell is charged when you step into it.
-
Moves go to one of the four neighboring cells. There are no diagonal moves and no moves outside the grid.
-
Every cell can be entered, so a path from
start
to
end
always exists.
Constraints
-
1 <= m, n <= 100
-
grid[i][j]
is one of
'W'
,
'B'
,
'C'
,
'T'
-
0 <= start[0] < m
and
0 <= start[1] < n
-
0 <= end[0] < m
and
0 <= end[1] < n
Examples
Input: grid = [["W","B","T"],["W","C","T"],["W","W","T"]], start = [0,0], end = [2,2]
Output: 8
The route (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) costs 5 + 1 + 1 + 1 = 8. Any route needs at least four moves and its first move costs 5 (Bike) or 10 (Walk), so no route is cheaper than 8.
Input: grid = [["T","T","T","T"],["W","W","W","T"],["T","T","T","T"]], start = [0,0], end = [2,0]
Output: 8
Going straight down costs 10 + 1 = 11 because it steps into a Walk cell. The route along the top row, down the Train column on the right and back along the bottom row makes eight moves into Train cells, for a total of 8.
Input: grid = [["C","W"]], start = [0,1], end = [0,0]
Output: 2
The only move steps into the Car cell, which costs 2. The Walk cell you start on is not charged.