omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / knights-tour / oracle.py
| 1 | # Independent reference for "Knight's tour" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | moves = [(2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)] |
| 4 | def onward(f, r, seen): |
| 5 | return [(f + dx, r + dy) for dx, dy in moves |
| 6 | if 0 <= f + dx < 8 and 0 <= r + dy < 8 and (f + dx, r + dy) not in seen] |
| 7 | path = [(0, 0)] |
| 8 | seen = {(0, 0)} |
| 9 | while len(path) < 64: |
| 10 | cands = onward(*path[-1], seen) |
| 11 | assert cands, "Warnsdorff dead end" |
| 12 | nxt = min(cands, key=lambda s: len(onward(*s, seen))) # min keeps the first of equal keys |
| 13 | path.append(nxt) |
| 14 | seen.add(nxt) |
| 15 | # the tour must be 64 distinct squares, each a knight's move from the one before |
| 16 | assert len(set(path)) == 64 |
| 17 | assert all(sorted((abs(a[0] - b[0]), abs(a[1] - b[1]))) == [1, 2] for a, b in zip(path, path[1:])) |
| 18 | num = {s: i + 1 for i, s in enumerate(path)} |
| 19 | print("Warnsdorff tour from a1; each square shows its move number, rank 8 at the top") |
| 20 | for r in range(7, -1, -1): |
| 21 | print("".join(f"{num[(f, r)]:3}" for f in range(8))) |