有py大佬看看为什么不行吗
查看原帖
有py大佬看看为什么不行吗
937288
wyzkeyy楼主2024/4/7 23:50
from queue import Queue
be = input()
ed = "123804765"
dxy = [(1, 0), (-1, 0), (0, 1), (0, -1)]
que = Queue()
que.put(be)
st = {be: 0}
while que.qsize():
    s = que.get()
    if s == ed:
        break
    z = s.index("0")
    x, y = z // 3, z % 3
    for dx, dy in dxy:
        nx, ny = x+dx, y+dy
        nz = nx*3+ny
        if 0 <= nz < 9:
            i1, i2 = min(z, nz), max(z, nz)
            ns = s[:i1]+s[i2]+s[i1+1:i2]+s[i1]+s[i2+1:]
            if st.get(ns, -1) == -1:
                st[ns] = st[s]+1
                que.put(ns)
res = st[ed]
print(res)

2024/4/7 23:50
加载中...