AcWing BFS相关问题 1107. 魔板

import sys
sys.stdin = open('data.txt', 'r')

'''
BFS 状态拓展应用
'''

from collections import deque

target = list( map(int, input().split()) )

def hash(arr):
    ans = 0
    base = 1
    for i in range(8):
        ans += arr[i] * base
        base *= 10
    return ans

def bfs(init_arr, target):
    que = deque()
    que.append(tuple(init_arr))
    prev = { hash(init_arr): (None, None) }

    step = 0
    flag = False
    while len(que) > 0:
        node_num = len(que)

        for _ in range(node_num):
            cur = list(que.popleft())
            if tuple(cur) == tuple(target):
                flag = True
                break

            A_stat = (cur[7], cur[6], cur[5], cur[4], cur[3], cur[2], cur[1], cur[0])
            B_stat = (cur[3], cur[0], cur[1], cur[2], cur[5], cur[6], cur[7], cur[4])
            C_stat = (cur[0], cur[6], cur[1], cur[3], cur[4], cur[2], cur[5], cur[7])

            if hash(A_stat) not in prev:
                prev[hash(A_stat)] = ('A', cur)
                que.append(A_stat)
            if hash(B_stat) not in prev:
                prev[hash(B_stat)] = ('B', cur)
                que.append(B_stat)
            if hash(C_stat) not in prev:
                prev[hash(C_stat)] = ('C', cur)
                que.append(C_stat)

        if flag:
            break
        step += 1

    path = []
    cur = tuple(target)
    while cur:
        key = hash(cur)
        if prev[key][0] is not None:
            path.append(prev[hash(cur)][0])
        cur = prev[hash(cur)][1]

    return step, path[::-1]

path_len, path = bfs([1,2,3,4,5,6,7,8], target)
print(path_len)
if len(path) > 0:
    print(''.join(path))

 

你可能感兴趣的:(AcWing,BFS相关问题,算法)