如何为 tsp 实现贪婪算法,其中并非所有节点都连接到其他节点

How to implement greedy algorithm for the tsp where not all nodes are connected to every other node

提问人:Michael2005 提问时间:10/22/2023 最后编辑:Andrej KeselyMichael2005 更新时间:10/22/2023 访问量:53

问:

并非所有节点都相互连接,如下所示,这意味着我当前的算法不起作用,因为它最终会访问所有节点,然后使用不存在的边,因为我已将它们在邻接矩阵中的值设置为无限大

e.g:

到目前为止,这就是我所拥有的

def tsp_greedy(self,adjacency_matrix, start_node):
    adjacency_matrix = np.where(adjacency_matrix == 0, np.inf, adjacency_matrix)
    print(adjacency_matrix)
    num_nodes = adjacency_matrix.shape[0]
    tour = [start_node]
    unvisited_nodes = list(range(num_nodes))
    unvisited_nodes.remove(start_node)
    
    while unvisited_nodes:
        current_node = tour[-1]
        nearest_neighbor = min(unvisited_nodes, key=lambda node: (adjacency_matrix[current_node][node], node))
        if adjacency_matrix[current_node][nearest_neighbor] == np.inf:
            break  # If the only remaining paths have infinite distance, break the loop
        tour.append(nearest_neighbor)
        unvisited_nodes.remove(nearest_neighbor)
    
    tour.append(start_node)
    total_distance = sum(adjacency_matrix[tour[i]][tour[i + 1]] for i in range(num_nodes))

    return tour, total_distance
python 算法 贪婪的 旅行推销员

评论

0赞 Andrej Kesely 10/22/2023
您自己实现这样的算法而不使用库,例如 ?networkx
0赞 ravenspoint 10/22/2023
在成本极高的未连接节点之间添加链接。如果可能,TSP 将避免这些链接。如果没有,那么就没有实际的解决方案。
0赞 Michael2005 10/22/2023
@AndrejKesely学校的项目,我因为使用 Networkx 等库来帮助我而被打分
0赞 Luatic 10/22/2023
如果你的要求不是找到一个精确的解决方案,那么近似值应该有多好?
1赞 user3386109 10/22/2023
您可以使用像 Dijkstra 这样的算法来查找从给定节点到其他每个节点的最短距离。然后,您可以使用这些距离创建完整的图表。

答: 暂无答案