omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / maze-solving / oracle.py
| 1 | # Independent reference for "Maze solving" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | M = 2 ** 64 |
| 4 | x = 0 |
| 5 | def rnd(): |
| 6 | global x |
| 7 | x = (x * 6364136223846793005 + 1442695040888963407) % M |
| 8 | return x >> 33 |
| 9 | W, H = 10, 6 |
| 10 | def generate(): |
| 11 | east = [[True] * W for _ in range(H)] |
| 12 | south = [[True] * W for _ in range(H)] |
| 13 | seen = {(0, 0)} |
| 14 | stack = [(0, 0)] |
| 15 | while stack: |
| 16 | r, k = stack[-1] |
| 17 | cands = [(r + dr, k + dk) for dr, dk in ((-1, 0), (0, 1), (1, 0), (0, -1)) |
| 18 | if 0 <= r + dr < H and 0 <= k + dk < W and (r + dr, k + dk) not in seen] |
| 19 | if not cands: |
| 20 | stack.pop() |
| 21 | continue |
| 22 | nr, nk = cands[rnd() % len(cands)] |
| 23 | if nr == r: |
| 24 | east[r][min(k, nk)] = False |
| 25 | else: |
| 26 | south[min(r, nr)][k] = False |
| 27 | seen.add((nr, nk)) |
| 28 | stack.append((nr, nk)) |
| 29 | return east, south |
| 30 | def draw(east, south, marked=()): |
| 31 | print("+" + "---+" * W) |
| 32 | for r in range(H): |
| 33 | print("|" + "".join((" * " if (r, k) in marked else " ") + ("|" if east[r][k] else " ") for k in range(W))) |
| 34 | print("+" + "".join("---+" if south[r][k] else " +" for k in range(W))) |
| 35 | east, south = generate() |
| 36 | def open_moves(r, k): |
| 37 | if r > 0 and not south[r - 1][k]: yield (r - 1, k) |
| 38 | if k < W - 1 and not east[r][k]: yield (r, k + 1) |
| 39 | if r < H - 1 and not south[r][k]: yield (r + 1, k) |
| 40 | if k > 0 and not east[r][k - 1]: yield (r, k - 1) |
| 41 | # depth-first search for the path; a perfect maze has exactly one |
| 42 | def dfs(cell, prev, goal): |
| 43 | if cell == goal: |
| 44 | return [cell] |
| 45 | for nxt in open_moves(*cell): |
| 46 | if nxt != prev: |
| 47 | p = dfs(nxt, cell, goal) |
| 48 | if p: |
| 49 | return [cell] + p |
| 50 | return None |
| 51 | path = dfs((0, 0), None, (H - 1, W - 1)) |
| 52 | draw(east, south, set(path)) |
| 53 | print("cells on the path from top left to bottom right:", len(path)) |