Shortest Path (Dynamic Programming)

Visualizing Top-Down Approach: Recursion + Memoization

Time Complexity: O(M × N) Space Complexity: O(M × N)

Cost Grid

Steps: 0

Legend

Unvisited
Evaluating (Call)
Cache Hit (Saved)
DP Computed
Optimal Path
Pseudocode (Recursion + Memoization)

function minPath(r, c) {
// Check bounds limits
if (r >= ROWS || c >= COLS) return Infinity;
// Base Case: Reached destination
if (r === ROWS - 1 && c === COLS - 1)
return grid[r][c];
// Memoization: Return early if computed
if (memo[r][c] !== null)
return memo[r][c];
// Recursion: Try moving RIGHT and DOWN
let rightCost = minPath(r, c + 1);
let downCost = minPath(r + 1, c);
// Store current cost + min path of children
memo[r][c] = grid[r][c] + Math.min(rightCost, downCost);
return memo[r][c];
}
Call Stack Logs READY
System waiting...