其他分享
首页 > 其他分享> > 水壶问题

水壶问题

作者:互联网

365. 水壶问题

有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水?

如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。

你允许:

示例 1: (From the famous "Die Hard" example)

输入: x = 3, y = 5, z = 4
输出: True

示例 2:

输入: x = 2, y = 6, z = 5
输出: False

分析一下x = 3, y = 5, z = 4的情况,最终需要4, 5-1=4,所以构造出一个1就可以,5-3=2,3-2=1

  1. x空,装满y
  2. y倒入x直到x装满,y剩下2
  3. x倒掉,y倒入x(此时x为2,y空)
  4. y装满,倒入x直到x满(此时x为3,y等于4)
  5. 倒出x
# DFS  搜索操作:清空、装满、倒入
def canMeasureWater(x,y,z):
    if x+y<z:
        return False
    if x ==0 or y == 0:
        return z == 0 or x+y == z
    stack = [(0,0)]#初始化x,y
    seen = set()
    while stack:
        remain_x,remain_y = stack.pop()
        if remain_x+remain_y == z:
            return True
        if (remain_x,remain_y) in seen:
            continue
        seen.add((remain_x,remain_y))
        stack.append((x, remain_y))# 把 X 壶灌满
        stack.append((remain_x, y))# 把 Y 壶灌满
        stack.append((0, remain_y))# 把 X 壶倒空
        stack.append((remain_x, 0))# 把 Y 壶倒空
        # 把 X 壶的水灌进 Y 壶,直至灌满或倒空
        stack.append((remain_x - min(remain_x, y - remain_y), remain_y + min(remain_x, y - remain_y)))
        # 把 Y 壶的水灌进 X 壶,直至灌满或倒空
        stack.append((remain_x + min(remain_y, x - remain_x), remain_y - min(remain_y, x - remain_x)))
    return False
# BFS  搜索操作:清空、装满、倒入
def canMeasureWater(x,y,z):
    if x+y<z:
        return False
    if x ==0 or y == 0:
        return z == 0 or x+y == z
    queue = [(0,0)]#初始化x,y
    seen = set()
    while queue:
        remain_x,remain_y = queue.pop(0)
        if remain_x+remain_y == z:
            return True
        if (remain_x,remain_y) in seen:
            continue
        seen.add((remain_x,remain_y))
        queue.append((x, remain_y))# 把 X 壶灌满
        queue.append((remain_x, y))# 把 Y 壶灌满
        queue.append((0, remain_y))# 把 X 壶倒空
        queue.append((remain_x, 0))# 把 Y 壶倒空
        # 把 X 壶的水灌进 Y 壶,直至灌满或倒空
        queue.append((remain_x - min(remain_x, y - remain_y), remain_y + min(remain_x, y - remain_y)))
        # 把 Y 壶的水灌进 X 壶,直至灌满或倒空
        queue.append((remain_x + min(remain_y, x - remain_x), remain_y - min(remain_y, x - remain_x)))
    return False
#裴蜀定理
def canMeasureWater(x,y,z):
    import math
    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

标签:return,水壶,装满,问题,倒入,canMeasureWater,def
来源: https://www.cnblogs.com/gongyanzh/p/12539082.html