Skip to content

Commit 9303509

Browse files
unique paths
1 parent 238766a commit 9303509

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

‎Common/src/utils/CommonUtils.java

+11
Original file line numberDiff line numberDiff line change
@@ -112,5 +112,16 @@ public static void printList(final ListNode head) {
112112
}
113113
System.out.println();
114114
}
115+
116+
public static void printMatrix(int[][] matrix) {
117+
System.out.println("Matrix is: ");
118+
for(int i = 0; i < matrix.length; i++){
119+
for(int j = 0; j < matrix[0].length; j++){
120+
System.out.print(matrix[i][j] + "\t");
121+
}
122+
System.out.println();
123+
}
124+
System.out.println("----------------------------------------------------");
125+
}
115126

116127
}

‎MEDIUM/src/medium/UniquePaths.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package medium;
2+
3+
import utils.CommonUtils;
4+
5+
/**Leetcode 62. Unique Paths
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 the bottom-right corner of the grid (marked 'Finish' in the diagram below).
10+
11+
How many possible unique paths are there?*/
12+
public class UniquePaths {
13+
14+
/**Another typical DP question, use a 2d array:
15+
* the first row and the first column need to be initialized to be 1 since there's only one way to reach every
16+
* position in the first row and the first column: either from left or top.*/
17+
public int uniquePaths(int m, int n) {
18+
int[][] dp = new int[m][n];
19+
for(int i = 0; i < m; i++) dp[i][0] = 1;
20+
for(int i = 0; i < n; i++) dp[0][i] = 1;
21+
22+
for(int i = 1; i < m; i++){
23+
for(int j = 1; j < n; j++){
24+
int ways = 0;
25+
if(i-1 >= 0) ways += dp[i-1][j];
26+
if(j-1 >= 0) ways += dp[i][j-1];
27+
dp[i][j] = ways;
28+
}
29+
}
30+
CommonUtils.printMatrix(dp);
31+
return dp[m-1][n-1];
32+
}
33+
34+
public static void main(String...strings){
35+
UniquePaths test = new UniquePaths();
36+
int m = 1;
37+
int n = 2;
38+
System.out.println(test.uniquePaths(m, n));
39+
}
40+
}

0 commit comments

Comments
 (0)