30L,17L,13L容器分油,python递归,深度优先算法

时间:2024-07-28 11:34:32

30L,17L,13L容器分油,python递归,深度优先算法

30L,17L,13L容器分油,python递归,深度优先算法

30L,17L,13L容器分油,python递归,深度优先算法

伪代码:

30L,17L,13L容器分油,python递归,深度优先算法

全部代码:

a=[]
b=[]
def f(x,y,z):
    b.append([x,y,z])
    if x==15 and y==15:
        print(x,y,z)
        i=0;
        for x in b:
            print(i,x,end="\n")
            i+=1
        exit()
    if [x,y,z] not in a:
        a.append([x,y,z])

    else:
        b.pop()
        return
    y1,y2,y3=30-x,17-y,13-z
    xt,yt,zt = 0,0,0
    # way1:
    if x>y2:
        xt,yt,zt=x-y2,17,z
    else:
        xt,yt,zt=0,y+x,z
    f(xt,yt,zt)
    # way2:
    if x>y3:
        xt,yt,zt=x-y3,y,13
    else:
        xt,yt,zt=0,y,z+x
    f(xt,yt,zt)

    # way3:
    if y>y1:
        xt,yt,zt=30,y-y1,z
    else:
        xt,yt,zt=x+y,0,z
    f(xt,yt,zt)
    # way4:
    if y>y3:
        xt,yt,zt=x,y-y3,13
    else:
        xt,yt,zt=x,0,z+y
    f(xt,yt,zt)

    # way5:
    if z>y1:
        xt,yt,zt=30,y,z-y1
    else:
        xt,yt,zt=x+z,y,0
    f(xt,yt,zt)
    # way6:
    if z>y2:
        xt,yt,zt=x,17,z-y2
    else:
        xt,yt,zt=x,y+z,0
    f(xt,yt,zt)

f(30,0,0)

运行结果:

15 15 0
0 [30, 0, 0]
1 [13, 17, 0]
2 [0, 17, 13]
3 [17, 0, 13]
4 [17, 13, 0]
5 [4, 13, 13]
6 [4, 17, 9]
7 [21, 0, 9]
8 [21, 9, 0]
9 [8, 9, 13]
10 [8, 17, 5]
11 [25, 0, 5]
12 [25, 5, 0]
13 [12, 5, 13]
14 [12, 17, 1]
15 [29, 0, 1]
16 [29, 1, 0]
17 [16, 1, 13]
18 [16, 14, 0]
19 [3, 14, 13]
20 [3, 17, 10]
21 [20, 0, 10]
22 [20, 10, 0]
23 [7, 10, 13]
24 [7, 17, 6]
25 [24, 0, 6]
26 [24, 6, 0]
27 [11, 6, 13]
28 [11, 17, 2]
29 [28, 0, 2]
30 [28, 2, 0]
31 [15, 2, 13]
32 [15, 15, 0]
[Finished in 0.1s]