leetcode:那些年我遇到过的编程题007:水壶问题
程序员文章站
2022-03-13 21:25:43
...
leetcode:那些年我遇到过的编程题007:水壶问题
实话实说,想了还挺久,思路停留在把每一个操作转化为计算机语言,没有找到最后判定false的点,那么思路一定是有问题的或者错误的,前边的也没有意义了。看了下答案,一种是用广度优先搜索,要用到hashset和queue队列,一种是用了数学定理。
广度优先搜索:
class Solution {
private LinkedList<State> queue;
private Set<State> visited;
private void Handle(State state){
if(!visited.contains(state)){
queue.offer(state);
visited.add(state);
}
}
private boolean bfs(State state, int z) {
int x = state.x;
int y = state.y;
queue = new LinkedList<>();
queue.add(new State(0,0));
visited = new HashSet<>();
visited.add(new State(0,0));
while (!queue.isEmpty()) {
while (!queue.isEmpty()){
State node = queue.poll();
int curX = node.x;
int curY = node.y;
if (curX + curY == z || curX == z || curY == z) {
return true;
}
if (curX == 0) {
Handle(new State(x,curY));
}
if (curY == 0) {
Handle(new State(curX,y));
}
// 有水的时候,才需要倒掉
if (curX > 0) {
Handle(new State(0,curY));
}
if (curY > 0) {
Handle(new State(curX,0));
}
if (curX - (y - curY) > 0) {
Handle(new State(curX - (y - curY), y));
}
if (curY - (x - curX) > 0) {
Handle(new State(x, curY - (x - curX)));
}
if (curX + curY < y) {
Handle(new State(0, curX + curY));
}
if (curX + curY < x) {
Handle(new State(curX + curY, 0));
}
}
}
return false;
}
public boolean canMeasureWater(int x, int y, int z) {
if(z==0) return true;
if(z > x + y) return false;
State state = new State(x,y);
return bfs(state, z);
}
private class State{
private int x;
private int y;
public State(int x,int y){
this.x = x;
this.y = y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public boolean equals(Object o){
if(this == o) return true;
if(o == null||getClass() != o.getClass()) return false;
State state = (State)o;
return x == state.x&&y ==state.y;
}
public int hashCode(){
return Objects.hash(x,y);
}
}
}
数学方法:
class Solution:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
if x + y < z:
return False
if x == 0 or y == 0:
return z == 0 or x + y == z
return z % math.gcd(x, y) == 0
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/water-and-jug-problem/solution/shui-hu-wen-ti-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。