Minimum Path Cost in a Grid - Dynamic Programming [JS]

Description 

Solution: Dynamic Programming

We only need information about the previous and current row.
Use two arrays of size n (prev and curr) to keep track of the minimum cost to travel to each cell in a row.
For each cell in a row, take the minimum cost of going from each cell in the previous row.

m = number of rows,n = number of columns
Time Complexity: O(m * n * n)174ms
Space Complexity: O(n) 55.5MB

var minPathCost = function(grid, moveCost) {
  let m = grid.length, n = grid[0].length;
  let prev = [...grid[0]];
  for (let i = 1; i < m; i++) { 
    let curr = Array(n).fill(Infinity);
    for (let j = 0; j < n; j++) { // curr row's columns
      for (let k = 0; k < n; k++) { // prev row's columns
        let prevCell = grid[i - 1][k], currCell = grid[i][j];
        curr[j] = Math.min(prev[k] + moveCost[prevCell][j] + currCell, curr[j]);
      }
    }
    prev = curr;
  }
  return Math.min(...prev);
};

javascript

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]