omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / dijkstras-algorithm / oracle.py
| 1 | # Independent reference for "Dijkstra's algorithm" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | def 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 |
| 11 | def 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, not by a priority queue |
| 18 | adj = {"a": {"b": 7, "c": 9, "f": 14}, "b": {"c": 10, "d": 15}, "c": {"d": 11, "f": 2}, "d": {"e": 6}, "e": {"f": 9}} |
| 19 | for t in "bcdef": |
| 20 | r = best(adj, "a", t) |
| 21 | if r is None: |
| 22 | print(f"a -> {t} unreachable") |
| 23 | else: |
| 24 | print(f"a -> {t} cost {r[0]} path " + " ".join(r[1])) |