interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / floyd-warshall-algorithm / oracle.py

24 lines · 1028 bytes Raw Blame History
1# Independent reference for "Floyd-Warshall algorithm" (Python 3, standard library only).
2# expected.txt is this program's stdout; omc never produced it.
3def simple_paths(adj, s, t, seen=()):
4 if s == t:
5 yield (s,)
6 return
7 for v in adj.get(s, {}):
8 if v not in seen and v != s:
9 for p in simple_paths(adj, v, t, seen + (s,)):
10 yield (s,) + p
11def best(adj, s, t):
12 cands = sorted((sum(adj[p[i]][p[i + 1]] for i in range(len(p) - 1)), p) for p in simple_paths(adj, s, t))
13 if not cands:
14 return None
15 assert len(cands) == 1 or cands[0][0] < cands[1][0], "shortest path not unique"
16 return cands[0]
17# checked by enumerating every simple path (there is no negative cycle), not by the triple loop
18adj = {1: {3: -2}, 2: {1: 4, 3: 3}, 3: {4: 2}, 4: {2: -1}}
19print("pair dist path")
20for i in range(1, 5):
21 for j in range(1, 5):
22 if i != j:
23 d, p = best(adj, i, j)
24 print(f"{i} -> {j}{d:>6} " + " -> ".join(map(str, p)))