zoukankan      html  css  js  c++  java
  • 双向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)
    
  • 相关阅读:
    Mybatis批量插入
    easyui中datagrid常见功能
    mysql下载和安装方式
    Mybatis注意事项
    ol3对地图上某些特定的经纬度进行标注
    ol3开发离线地图
    java利用poi生成excel文件后下载本地
    log4j的基本使用方法
    tomcat8.5之后版本,远程无法登录管理页面
    但构造函数返回对象时
  • 原文地址:https://www.cnblogs.com/NFii/p/12623440.html
Copyright © 2011-2022 走看看