双向BFS / 蓝桥杯 - 翻硬币(宽搜思路,待改进)

双向BFS的模板
"""
BFS双向的模板:适用于从某个初始状态到某个终止状态求最短路径

head = {初始状态}
tail = {终止状态}

while head and tail:
    # 每次都从短的开始
    if len(head) > len(tail):
        head, tail = tail, head

    nextLeval = set()
    for i in head:
        # 扩展下一层
        if 扩展的下一层的某个元素 in tail:
            # 表示已经找到了
            return

    head = nextLevel
    # 每次的head和tail都在更新为某层的状态

"""

翻硬币


"""
提到了起始状态和终止状态所以想到利用双向BFS,但是超时了(只过了第一个用例),尝试将字符串拆分再去BFS仍然超时,待改进。
"""
s = list(input(""))
e = list(input(""))
# 转换为数字再进行修改
def change(arr):
    for i in range(len(arr)):
        if arr[i] == '*':
            arr[i] = 1
        else:
            arr[i] = -1
    return arr
# 套用双向BFS模板
def BFS(s, e):
    head, tail, vis = [s], [e], []
    step = 0
    while head and tail:
        if len(head) > len(tail):
            head, tail = tail, head
        step += 1
        nextLevel = []
        for i in head:
            if i in vis:
                continue
            vis.append(i)
            # 扩展下一层
            for j in range(len(i) - 1):
                s = i.copy()
                s[j] = -s[j]
                s[j + 1] = -s[j + 1]
                if s in tail:
                    return step
                nextLevel.append(s)
        head = nextLevel
    return 0

start = -1
for i in range(len(s)):
    if s[i] != e[i]:
        if start == -1:
            start = i
        else:
            sum += BFS(change(s[start:i+1]), change(e[start:i+1]))
            start = -1
print(sum)

猜你喜欢

转载自www.cnblogs.com/NFii/p/12623440.html
今日推荐