62 Unique Paths
Last updated
Last updated
A robot is located at the top-left corner of amxngrid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note :m and n will be at most 100.
Approach 1: Brute Force
The Idea: One solution is to look options we have available at every cell (i,j). Since we have the option to only move down or right this simplifies the problem. For example, if we are in row 2, and there are 3 rows, then we only have the option to move down another row. Likewise, if we are on the 4th column and there are total of 7 columns, then we can move to the right 3 more places. In general, the cell we are under will provide us with available options we have left. Finally, the available paths can summarizes as the root to leaf paths, and the total number of paths are then just the number of leaves. There some obvious improvements here, but the purpose was just to demonstrate a brute force approach.
Approach 2: Dynamic Programming
Complexity: O(n*m) time and space. Space can actually be improved to be linear because if you think about it, the only cells we are interested in are the previous cells from above and to the right - and as long as we maintain a previous vector that consistently gets updated, we are good.
Complexity: O(2^n) time and O(2^n) space
The Idea: A better approach would be to try and identify the relationship between the cells as the matrix grows larger. Since we can only move down and right, the total number of paths are simply the number of ways that are approached from the left and above.