Unique Paths
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.Thoughts:
Of course, this can be solved by applying either DFS or BFS on a directed graph. Any better solution?
Since the robot can only choose "right" or "down", the total number of each movement are fixed to (m+n-2). We can first pick up (m-1) "down" moves, and the other movements can be "right" direction only.
So the total number of unique paths are Combination(m+n-2, m-1).
The combination has factorial calculations, so we have to be careful avoiding overflow. Here the algorithm is taken from TAOCP.
Solution:
- class Solution {
- public:
- unsigned long long
- choose(unsigned long long n, unsigned long long k) {
- if (k > n) {
- return 0;
- }
- unsigned long long r = 1;
- for (unsigned long long d = 1; d <= k; ++d) {
- r *= n--;
- r /= d;
- }
- return r;
- }
- int uniquePaths(int m, int n) {
- if (m == 1 || n == 1)
- return 1;
- if (m < n) swap(m, n);
- return choose(m+n-2, n-1);
- }
- };
No comments:
Post a Comment