Description
Solutions
Submission
Minimum Cost to Move Within a Grid (Akuna Shang Hai 🌃)
🔥 FULLTIME

A player stands on a cell within a grid. The player can move to one of four adjacent cells, but the motion is constrained by lasers. To move from one position to another involves a cost: the cost to move from row i to row i ± 1 is costRows[i] and the cost to move from column j to column j ± 1 is costCols[j]. Find the minimum cost to move from a starting point to an ending point within the grid.

Function Description

Complete the function minCost in the editor below.

minCost has the following parameters:

  1. int rows: the number of rows in the grid
  2. int cols: the number of columns in the grid
  3. int initR: the player's starting row
  4. int initC: the player's starting column
  5. int finalR: the goal's row
  6. int finalC: the goal's column
  7. int costRows[n]: each costRows[i] denotes the cost to move between rows i and i + 1.
  8. int costCols[m]: each costCols[j] denotes the cost to move between columns j and j + 1.

Returns

int: the minimum cost to move from the starting position to the goal

Example 1:

Input:  rows = 3, cols = 3, initR = 0, initC = 0, finalR = 1, finalC = 2, costRows = [5, 2], costCols = [6, 1]
Output: 9
Explanation:
The player must move down one row (cost = 2) and over two columns (cost = 6 + 1 = 7) for a total cost of 2 + 7 = 9.

Example 2:

Input:  rows = 4, cols = 4, initR = 1, initC = 2, finalR = 3, finalC = 3, costRows = [1, 2, 3], costCols = [7, 8, 9]
Output: 14
Explanation:
The player must move from row 1 to row 3 for a cost = 2 + 3 = 5 and then from column 2 to column 3 for a cost of 9. The total cost is 5 + 9 = 14.
Constraints:
    • 1 ≤ rows, cols ≤ 105
    • 0 ≤ initR, finalR < rows
    • 0 ≤ initC, finalC < cols
    • 0 ≤ costRows[i] ≤ 104 (0 ≤ i < rows-1)
    • 0 ≤ costCols[j] ≤ 104 (0 ≤ j < cols-1)
Thumbnail 0
Testcase

Result
Case 1

input:

output: