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
36
37
38
39
40
41
42
43
|
func min(nums ...int) int {
res := nums[0]
for _, num := range nums {
if num < res {
res = num
}
}
return res
}
func canMeasureWater(jug1Capacity int, jug2Capacity int, targetCapacity int) bool {
seen := make(map[[2]int]bool)
var stack [][2]int
stack = append(stack, [2]int{0, 0})
for len(stack) > 0 {
cur := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if seen[cur] {
continue
}
seen[cur] = true
remainX, remainY := cur[0], cur[1]
if remainX == targetCapacity || remainY == targetCapacity ||
remainX+remainY == targetCapacity {
return true
}
// 将第一个水壶倒满
stack = append(stack, [2]int{jug1Capacity, remainY})
// 清空第一个水壶
stack = append(stack, [2]int{0, remainY})
// 将第一个水壶的水壶倒入第二个水壶,直至水倒完或者第二个水壶的水倒满
stack = append(stack, [2]int{remainX - min(remainX, jug2Capacity-remainY),
remainY + min(remainX, jug2Capacity-remainY)})
// 将第二个水壶倒满
stack = append(stack, [2]int{remainX, jug2Capacity})
// 清空第二个水壶
stack = append(stack, [2]int{remainX, 0})
// 将第二个水壶的水倒入第一个水壶,直至水倒完或者第一个水壶的水倒满
stack = append(stack, [2]int{remainX + min(remainY, jug1Capacity-remainX),
remainY - min(remainY, jug1Capacity-remainX)})
}
return false
}
|