FastPrepShortest Path with Directional Move Costs
Problem · Graph

Shortest Path with Directional Move Costs

Learn this problem
MediumThe Walt Disney Company logoThe Walt Disney CompanyFULLTIMEPHONE SCREEN

Problem statement

You are given a rectangular character grid and an array directionCosts of four nonnegative integers. The grid contains exactly one start cell 'S', exactly one destination cell 'T', open cells '.', and blocked cells '#'.

You may move to an orthogonally adjacent non-blocked cell. The cost of moving up, right, down, or left is directionCosts[0], directionCosts[1], directionCosts[2], or directionCosts[3], respectively.

Return the minimum total cost required to reach 'T' from 'S'. The start cell contributes zero cost. Return -1 if the destination is unreachable.

Function

minimumTravelCost(grid: String[], directionCosts: int[]) → long

Examples

Example 1

grid = ["S..",".#T","..."]directionCosts = [3,1,4,2]return = 6

Move right twice and then down. The total cost is 1 + 1 + 4 = 6, which is minimum.

Example 2

grid = ["S#","#T"]directionCosts = [1,1,1,1]return = -1

Both cells adjacent to the start are blocked, so the destination cannot be reached.

Constraints

  • 1 <= grid.length <= 100.
  • 1 <= grid[i].length <= 100, and every row has the same length.
  • Every grid cell is 'S', 'T', '.', or '#'.
  • The grid contains exactly one 'S' and exactly one 'T'.
  • directionCosts.length == 4.
  • 0 <= directionCosts[i] <= 10^6.
drafts saved locally
public long minimumTravelCost(String[] grid, int[] directionCosts) {
    // write your code here
}
grid["S..",".#T","..."]
directionCosts[3,1,4,2]
expected6
checking account