-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathWaterAndJugProblem.java
30 lines (28 loc) · 1.03 KB
/
WaterAndJugProblem.java
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
/*https://leetcode.com/problems/water-and-jug-problem/*/
class Solution {
public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
int[] dir = {jug1Capacity,-jug1Capacity,jug2Capacity,-jug2Capacity};
if (targetCapacity > jug1Capacity+jug2Capacity) return false;
boolean[] visited = new boolean[jug1Capacity+jug2Capacity+1];
Queue<Integer> q = new LinkedList<>();
q.add(0);
visited[0] = true;
while (q.size() > 0)
{
int size = q.size();
while (size-- > 0)
{
int rem = q.remove();
if (rem == targetCapacity) return true;
for (int k = 0; k < 4; ++k)
{
int pos = rem+dir[k];
if (pos > jug1Capacity+jug2Capacity || pos < 0 || visited[pos] == true) continue;
q.add(pos);
visited[pos] = true;
}
}
}
return false;
}
}