Given a 2d matrix cost[][], calculate the minimum cost path from (0, 0) to (m, n). Only move down, right and diagonally lower cells from a given cell is allowed.
Building upon understanding of Min cost path (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def move(c, m, n): cache = [[0] * (n + 1) for _ in range(m + 1)] cache[0][0] = c[0][0] for i in range(1, m + 1): cache[i][0] = cache[i - 1][0] + c[i][0] for j in range(1, n + 1): cache[0][j] = cache[0][j - 1] + c[0][j] for i in range(1, m + 1): for j in range(1, n + 1): cache[i][j] = c[i][j] + min(cache[i - 1][j], cache[i][j - 1], cache[i - 1][j - 1]) return cache[m][n] cost = [ [1, 2, 3], [4, 8, 2], [1, 5, 3] ] target = [2, 2] print(move(cost, target[0], target[1]))
function move(c, m, n) { const cache = Array.from(Array(m + 1), () => Array(n + 1).fill(0)); cache[0][0] = c[0][0]; for (let i = 1; i < m + 1; i++) { cache[i][0] = cache[i - 1][0] + c[i][0]; } for (let j = 1; j < n + 1; j++) { cache[0][j] = cache[0][j - 1] + c[0][j] } for (let i = 1; i < m + 1; i++) { for (let j = 1; j < n + 1; j++) { cache[i][j] = c[i][j] + Math.min(cache[i - 1][j], cache[i][j - 1], cache[i - 1][j - 1]); } } return cache[m][n]; } const cost = [ [1, 2, 3], [4, 8, 2], [1, 5, 3] ]; const target = [2, 2]; console.log(move(cost, target[0], target[1]));