1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| import math
n = 5 dist = [ [0, 2, 5, 3, 7], [2, 0, 10, 6, 6], [5, 10, 0, 4, 8], [3, 6, 4, 0, 12], [7, 6, 8, 12, 0] ]
path = [] visited = [False for _ in range(n)]
def shortest_path1(path, visited, d):
if all(visited): return d+dist[path[-1]][path[0]]
cur = path[-1]
ret = math.inf for _next in range(n): if not visited[_next]: path.append(_next) visited[_next] = True ret = min(ret, shortest_path1(path, visited, d+dist[cur][_next])) path.pop() visited[_next] = False
return ret
path.append(0) visited[0] = True
if __name__ == "__main__": print(shortest_path1(path, visited, 0))
|