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

视频版

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))

 

posted @ 2021-04-25 19:20  会武术之白猫  阅读(566)  评论(0编辑  收藏  举报