A robot is located at the top-left corner of a m x n grid (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.
We can use DP to solve this problem. Assume grid[i][j] is the total paths to (i, j), it will be grid[i-1][j] + grid[i][j-1]. We can get to this spot from its left side or its upside if i and j are greater than 0. Otherwise we can only get there either only from its left side or only from its upside.
C++ Code:
/* * func: unique_path * goal: find the numbers of all unique paths from start to the end * @param m: the number of rows in the grid * @param n: the number of columns in the grid * return: the total numbers */ /* * Use dynamic programming, the path to the current spot is the path to its left * plus path to its upside. * complexity: time O(m*n), space O(m*n) */ int unique_path(int m, int n){ if(m < 0 || n < 0){ return 1; } int **grid = new int* [m]; for(int i=0; i<m; i++){ grid[i] = new int[n]; } grid[0][0]=1; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(i == 0 && j > 0){ grid[i][j] = grid[i][j-1]; }else if(i > 0 && j == 0){ grid[i][j] = grid[i-1][j]; }else if(i > 0 && j > 0){ grid[i][j] = grid[i-1][j] + grid[i][j-1]; } } } int result = grid[m-1][n-1]; for(int i=0; i<m; i++){ delete[] grid[i]; } delete [] grid; return result; }
Python Code:
# func: find the number of total unique paths to the target spot # @param m: the number of rows # @param n: the number of columns # @return: total numbers # complexity: time O(m*n), space O(m*n) def unique_paths(m, n): if m < 0 or n < 0: return 1 grid = [[1] * n for _ in xrange(m)] for i in xrange(m): for j in xrange(n): if i > 0 and j == 0: grid[i][j] = grid[i-1][j] elif i == 0 and j > 0: grid[i][j] = grid[i][j-1] elif i > 0 and j > 0: grid[i][j] = grid[i-1][j] + grid[i][j-1] return grid[m-1][n-1]
No comments:
Post a Comment