• 回溯法贪心法求旅行商问题


    视频版

    https://www.bilibili.com/video/BV1DQ4y1Z7u3/

     

     

     

     

     

     

    首先是回溯算法框架

    def template(input):
        result=[]
        def trace(path,choices):         #回溯函数
            if len(path)==len(input):    #结束条件
                result.append(list(path))#结果添加
                return                   #返回操作
            for item in choices:         #可选选择
                if item in path:continue #剪枝操作
                path.append(item)        #路径添加
                trace(path,choices)      #下一节点
                path.pop()               #路径回溯
        trace([],input)                  #运行函数
        return result                    #返回结果
    
    print(template([1,2,3]))

    然后是全程代码

    matrix=[[0,2,3,4],
            [2,0,6,8],
            [3,6,0,7],
            [4,8,7,0]]
    
    def sum_res(path,matrix):
        res=0
        path.append(path[0])
        for i in range(len(path)-1):
            res+=matrix[path[i]][path[i+1]]
        return res
    
    def template(input):
        result=[]
        def trace(path,choices):         #回溯函数
            if len(path)==len(input):    #结束条件
                result.append(list(path))#结果添加
                return                   #返回操作
            for i in range(len(choices)):         #可选选择
                if i in path or matrix[path[-1]][i]==0:continue #剪枝操作
                path.append(i)        #路径添加
                trace(path,choices)      #下一节点
                path.pop()               #路径回溯
        trace([0],input)                  #运行函数
        res=[]
        for item in result:
            res.append([sum_res(item,matrix),item])
        res.sort(key=lambda x:x[0])
        return res                    #返回结果
    
    def greedy(matrix):
        res=[0]
        while(len(res)!=len(matrix)):
            mid_que=[]
            mid_max=999
            mid_node=-1
            for i in range(len(matrix)):
                if matrix[res[-1]][i]!=0 and matrix[res[-1]][i]<mid_max and i not in res:
                    mid_max=matrix[res[-1]][i]
                    mid_node=i
            res.append(mid_node)
        return res
    #print(template(matrix))
    print(greedy(matrix))
  • 相关阅读:
    VMWare ESX Server
    ubuntu 13.04 xrdp 远程桌面连接问题[转载]
    wget 使用技巧
    C# 跨线程调用问题
    ASP.NET WEB API 返回JSON 出现2个双引号问题
    ASP.NET MVC 4 中Razor 视图中JS无法调试
    Android 如何修改gen下包的名字
    打开AVD时报”Data partition already in use. Changes will not persist!”
    Android 将APK文件安装到AVD中并分析其界面结构
    Android 实现界面(Activity)的跳转
  • 原文地址:https://www.cnblogs.com/ljy1227476113/p/14701666.html
Copyright © 2020-2023  润新知