-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGridWays.java
More file actions
65 lines (52 loc) · 1.7 KB
/
Copy pathGridWays.java
File metadata and controls
65 lines (52 loc) · 1.7 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
59
60
61
62
63
64
65
package backtracking;
// ----- Recursive Approach (Exponential) -----
// public class GridWays {
// public static int gridWays(int i, int j, int n, int m) {
// if ( i == n - 1 && j == m - 1) { // condition for last cell
// return 1;
// } else if (i == n || j == m) { // boundry cross condition
// return 0;
// }
// int ways1 = gridWays(i + 1, j, n, m);
// int ways2 = gridWays(i, j + 1, n, m);
// return ways1 + ways2;
// }
// public static void main(String[] args) {
// int n = 3, m = 3;
// System.out.println(gridWays(0, 0, n, m));
// }
// }
// TC: O(2^(n+m)) | SC: O(m + n)
// ----- Combinations Approach (Optimized) -----
public class GridWays {
public static int gridWays(int n, int m) {
int totalSteps = (n - 1) + (m - 1);
int steps = Math.min(n - 1, m - 1);
long res = 1;
for (int i = 1; i <= steps; i++) {
res = res * (totalSteps - steps + i) / i;
}
return (int) res;
}
public static void main(String[] args) {
int n = 3, m = 3;
System.out.println(gridWays(n, m));
}
}
// TC: O(min(n, m)) | SC: O(1)
// Find number of ways to reach from (0, 0) to ( n-1, m-1) in a N8m Grid. Allowed moves - right or down.
/*
Unique Paths (LeetCode 62)
https://leetcode.com/problems/unique-paths/description/
class Solution {
public int uniquePaths(int m, int n) {
int totalSteps = (m - 1) + (n - 1);
int steps = Math.min(m - 1, n - 1);
long res = 1;
for (int i = 1; i <= steps; i++) {
res = res * (totalSteps - steps + i) / i;
}
return (int) res;
}
}
*/