Overview
This is the "Hello World" of 2D grid DP. At any given cell, how did we get here? We must have come from either the cell directly above, or directly to the left.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find the number of possible unique paths from the top-left corner to the bottom-right corner of a grid, moving only Right or Down.
This is the "Hello World" of 2D grid DP. At any given cell, how did we get here? We must have come from either the cell directly above, or directly to the left.
Since we can only arrive from UP or LEFT, the total number of unique paths to a cell is simply the sum of the paths to those two source cells: `dp[r][c] = dp[r-1][c] + dp[r][c-1]`.
Any cell in the very first row can only be reached by moving continuously Right. So `dp[0][c] = 1`. Similarly, the first column is all `1`s.
This problem can also be solved in `O(min(M, N))` time using combinatorics: it's exactly `(M+N-2) Choose (M-1)`. But the DP approach is more extensible to obstacles.