提问人:Michael2005 提问时间:10/22/2023 最后编辑:Andrej KeselyMichael2005 更新时间:10/22/2023 访问量:53
如何为 tsp 实现贪婪算法,其中并非所有节点都连接到其他节点
How to implement greedy algorithm for the tsp where not all nodes are connected to every other node
问:
并非所有节点都相互连接,如下所示,这意味着我当前的算法不起作用,因为它最终会访问所有节点,然后使用不存在的边,因为我已将它们在邻接矩阵中的值设置为无限大
到目前为止,这就是我所拥有的
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
答: 暂无答案
评论
networkx