An interactive visualization of how dynamic programming counts unique paths in a grid. Watch the algorithm build up the solution from base cases to the final answer.
Dynamic Programming LeetCode 62 β Mediumm Γ n grid, starting at the top-left corner.m and n, return the number of unique paths the robot can take to reach the bottom-right corner.
fun uniquePaths(m: Int, n: Int): Int { val dp = Array(m) { IntArray(n) } for (i in 0 until m) { dp[i][0] = 1 // first column } for (j in 0 until n) { dp[0][j] = 1 // first row } for (i in 1 until m) { for (j in 1 until n) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1] } } return dp[m - 1][n - 1]}
The number of unique paths to reach any cell (i, j) is the sum of paths
from the cell above it (i-1, j) and the cell to its left (i, j-1).
This is because the robot can only arrive at (i, j) from these two directions.
1 path (can only move right).1 path (can only move down).
For any cell (i, j) where i > 0 and j > 0:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
m Γ n grid filled with zeros.dp[i][0] = 1 for all rows (base case).dp[0][j] = 1 for all columns (base case).(i, j), compute dp[i][j] = dp[i-1][j] + dp[i][j-1].dp[m-1][n-1] (bottom-right corner).We visit each cell exactly once to compute its value, giving us O(m Γ n) time complexity. The DP table requires O(m Γ n) space to store all intermediate results. Space optimization: Since each row only depends on the previous row, we can reduce space to O(n) by keeping only two rows in memory.