365. 水壺問題 題目鏈接
解法一:BFS
把問題化簡爲:尋找一條從 0 -> z 的路徑,每次可以有 6 種操作。
1、 將 X 倒滿
2、將 Y 倒滿
3、將 X 水倒出
4、將 Y 水倒出
5、將 X 水倒入 Y 中
6、將 Y 水導入 X 中
通過化簡我們可以將操作精簡爲:+x,+y,-x,-y。(3、5合併爲 -x,4、6合併爲 -y)
使用變量 cur 記錄當前狀態,visuted 散列表存儲已探索有效路徑,防止「迷路」(死循環),queue 記錄之前路徑,走不到目標時退回。
思路參考:https://leetcode.com/problems/water-and-jug-problem/discuss/172968/Java-BFS
public boolean canMeasureWater(int x, int y, int z) {
if (z < 0 || z > x + y) {
return false;
}
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
queue.add(0);
int[] options = {x, y, -x, -y};
while (!queue.isEmpty()) { // 隊列爲空說明無法找到滿足要求的路徑
int s = queue.size();
for (int i = 0; i < s; i++) {
int cur = queue.poll();
if (cur == z) {
return true;
}
for (int option : options) {
int next = cur + option;
if (next < 0 || next > x + y) { // 當前操作結果無效,無需存儲狀態
continue;
}
if (!visited.contains(next)) { // 對未探究路徑進行嘗試
if (next == z) {
return true;
}
queue.add(next);
visited.add(next);
}
}
}
}
解法二:基於數學的「貝祖定律」
public boolean canMeasureWater(int x, int y, int z) {
if (x == 0 && y == 0) {
return z == 0;
}
return z == 0 || (z % gcd(x, y) == 0 && x + y >= z);
}
/**
* 求最大公約數
* @param a
* @param b
* @return
*/
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}