|
3 | 3 | // Date : 2014-06-25
|
4 | 4 |
|
5 | 5 | /**********************************************************************************
|
6 |
| -* |
7 |
| -* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). |
8 |
| -* |
9 |
| -* The robot can only move either down or right at any point in time. The robot is trying to reach |
10 |
| -* the bottom-right corner of the grid (marked 'Finish' in the diagram below). |
11 |
| -* |
12 |
| -* How many possible unique paths are there? |
13 |
| -* |
14 |
| -* Above is a 3 x 7 grid. How many possible unique paths are there? |
15 |
| -* |
16 |
| -* Note: m and n will be at most 100. |
17 |
| -* |
18 |
| -**********************************************************************************/ |
| 6 | + * |
| 7 | + * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). |
| 8 | + * |
| 9 | + * The robot can only move either down or right at any point in time. The robot is trying to reach |
| 10 | + * the bottom-right corner of the grid (marked 'Finish' in the diagram below). |
| 11 | + * |
| 12 | + * |
| 13 | + * start |
| 14 | + * +---------+----+----+----+----+----+ |
| 15 | + * |----| | | | | | | |
| 16 | + * |----| | | | | | | |
| 17 | + * +----------------------------------+ |
| 18 | + * | | | | | | | | |
| 19 | + * | | | | | | | | |
| 20 | + * +----------------------------------+ |
| 21 | + * | | | | | | |----| |
| 22 | + * | | | | | | |----| |
| 23 | + * +----+----+----+----+----+---------+ |
| 24 | + * finish |
| 25 | + * |
| 26 | + * |
| 27 | + * How many possible unique paths are there? |
| 28 | + * |
| 29 | + * Above is a 3 x 7 grid. How many possible unique paths are there? |
| 30 | + * |
| 31 | + * Note: m and n will be at most 100. |
| 32 | + * |
| 33 | + **********************************************************************************/ |
19 | 34 |
|
20 | 35 | #include <stdio.h>
|
21 | 36 | #include <stdlib.h>
|
22 | 37 |
|
23 | 38 | void printMatrix(int*a, int m, int n);
|
24 | 39 |
|
| 40 | +/* |
| 41 | + * Dynamic Programming |
| 42 | + * |
| 43 | + * We have a dp[i][j] represents how many paths from [0][0] to hear. So, we have the following DP formuler: |
| 44 | + * |
| 45 | + * dp[i][j] = 1 if i==0 || j==0 //the first row/column only have 1 uniqe path. |
| 46 | + * = dp[i-1][j] + dp[i][j-1] //the path can be from my top cell and left cell. |
| 47 | + */ |
25 | 48 | int uniquePaths(int m, int n) {
|
26 | 49 | int* matrix = new int[m*n];
|
27 | 50 | printMatrix(matrix, m, n);
|
@@ -58,7 +81,7 @@ int main(int argc, char** argv)
|
58 | 81 | m = atoi(argv[1]);
|
59 | 82 | n = atoi(argv[2]);
|
60 | 83 | }
|
61 |
| - |
| 84 | + |
62 | 85 | printf("uniquePaths=%d\n", uniquePaths(m,n));
|
63 | 86 | return 0;
|
64 | 87 | }
|
0 commit comments