您可以通过跟踪当前的房子和到目前为止访问过的所有房屋来尝试减少要检查的路径数量。假设你有路径[1, 2, 3, 4]和[1, 3, 2, 4],你可以检查哪一条短一些,然后继续。下面是一个使用您提供的数据的示例,它将距离存储在2D数组中,而不是dict,但原理是相同的:dist = [
[0, 74, 4109, 3047, 2266],
[74, 0, 4069, 2999, 2213],
[4109, 4069, 0, 1172, 1972],
[3047, 2999, 1172, 0, 816],
[2266, 2213, 1972, 816, 0]
]
# Helper function to calculate path length
def path_len(path):
return sum(dist[i][j] for i, j in zip(path, path[1:]))
# Set of all nodes to visit
to_visit = set(xrange(len(dist)))
# Current state {(node, visited_nodes): shortest_path}
state = {(i, frozenset([0, i])): [0, i] for i in xrange(1, len(dist[0]))}
for _ in xrange(len(dist) - 2):
next_state = {}
for position, path in state.iteritems():
current_node, visited = position
# Check all nodes that haven't been visited so far
for node in to_visit - visited:
new_path = path + [node]
new_pos = (node, frozenset(new_path))
# Update if (current node, visited) is not in next state or we found shorter path
if new_pos not in next_state or path_len(new_path) < path_len(next_state[new_pos]):
next_state[new_pos] = new_path
state = next_state
# Find the shortest path from possible candidates
shortest = min((path + [0] for path in state.itervalues()), key=path_len)
print 'path: {0}, length: {1}'.format(shortest, path_len(shortest))
它将输出最短路径之一和总距离:
^{pr2}$
请注意,对于您提供的数据,有两个长度相等的可能解决方案:[0, 2, 3, 4, 1, 0]和{}。在