-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall-paths-in-a-matrix.java
More file actions
58 lines (43 loc) · 1.24 KB
/
all-paths-in-a-matrix.java
File metadata and controls
58 lines (43 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
A robot is located at the top-left corner of a m x n grid. It 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.
How many possible unique paths are there?
Java Solution 1 - DFS
A depth-first search solution is pretty straight-forward. However, the time of this solution is too expensive, and it didn't pass the online judge.
public int uniquePaths(int m, int n) {
return dfs(0,0,m,n);
}
public int dfs(int i, int j, int m, int n){
if(i==m-1 && j==n-1){
return 1;
}
if(i<m-1 && j<n-1){
return dfs(i+1,j,m,n) + dfs(i,j+1,m,n);
}
if(i<m-1){
return dfs(i+1,j,m,n);
}
if(j<n-1){
return dfs(i,j+1,m,n);
}
return 0;
}
Java Solution 2 - Dynamic Programming
public int uniquePaths(int m, int n) {
if(m==0 || n==0) return 0;
if(m==1 || n==1) return 1;
int[][] dp = new int[m][n];
//left column
for(int i=0; i<m; i++){
dp[i][0] = 1;
}
//top row
for(int j=0; j<n; j++){
dp[0][j] = 1;
}
//fill up the dp table
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}