forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWhereWillTheBallFall.java
More file actions
35 lines (29 loc) · 999 Bytes
/
WhereWillTheBallFall.java
File metadata and controls
35 lines (29 loc) · 999 Bytes
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
package graph;
/**
* Description: https://leetcode.com/problems/water-and-jug-problem
* Difficulty: Medium
* Time complexity: O(m * n)
* Space complexity: O(m)
*/
public class WhereWillTheBallFall {
public int[] findBall(int[][] grid) {
int[] result = new int[grid[0].length];
for (int ball = 0; ball < grid[0].length; ball++) {
result[ball] = fallDown(0, ball, grid);
}
return result;
}
private int fallDown(int row, int col, int[][] grid) {
if (row == grid.length) return col;
if (grid[row][col] == 1
&& col < grid[0].length - 1
&& grid[row][col] == grid[row][col + 1]) {
return fallDown(row + 1, col + 1, grid); // fall to the right
} else if (grid[row][col] == -1
&& col > 0
&& grid[row][col] == grid[row][col - 1]) {
return fallDown(row + 1, col - 1, grid); // fall to the left
}
return -1;
}
}