#!/usr/bin/env python3
# Refer to: http://wiki.jikexueyuan.com/project/easy-learn-algorithm/floyd.html
# Comments: The Floyd algorithm can tell how much the nearest path between 2 vertex costs
N = 4 # number of total vertex
original = 1000 # init cost of unconnected vertex with an infinity
# map in 2D grid to connect vertex with positive cost
cost = [[0, 2, 6, 4],
[original, 0, 3, original],
[7, original, 0, 1],
[5, original, 12, 0]]
shortest_path = [[[1, 1], [1, 2], [1, 3], [1, 4]],
[[2, 1], [2, 2], [2, 3], [2, 4]],
[[3, 1], [3, 2], [3, 3], [3, 4]],
[[4, 1], [4, 2], [4, 3], [4, 4]]]
def remove_duplicates(val):
output = []
seen = set()
for v in val:
if v not in seen:
output.append(v)
seen.add(v)
return output
for mid in range(N):
for i in range(N):
for j in range(N):
if (cost[i][mid] + cost[mid][j]) < cost[i][j]:
cost[i][j] = cost[i][mid] + cost[mid][j]
shortest_path[i][j] = []
shortest_path[i][j].extend(shortest_path[i][mid])
shortest_path[i][j].extend(shortest_path[mid][j])
for i in range(N):
#print(shortest_path[i])
for j in range(N):
shortest_path[i][j] = remove_duplicates(shortest_path[i][j])
print(shortest_path[i])
print(cost[i])