Skip to content

Instantly share code, notes, and snippets.

@thrasibule
Created December 11, 2023 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thrasibule/f5a7a9fdc828bc901aebd404295e37e7 to your computer and use it in GitHub Desktop.
Save thrasibule/f5a7a9fdc828bc901aebd404295e37e7 to your computer and use it in GitHub Desktop.
import sys
def first_pos(start, grid, m, n):
x, y = start
if x > 0 and grid[x-1][y] in ("|", "F", "7"):
return (x-1, y), "N"
if x < m-1 and grid[x+1][y] in ("|", "J", "L"):
return (x+1, y), "S"
if y > 0 and grid[x][y-1] in ("-", "F", "L"):
return (x, y-1), "W"
if y < n-1 and grid[x][y+1] in ("-", "7", "J"):
return (x, y+1), "E"
def next_pos(pos, grid, m, n, prev_dir):
x, y = pos
match grid[x][y], prev_dir:
case "F", "N":
return (x, y+1), "E"
case "F", "W":
return (x+1, y), "S"
case "|", "N":
return (x-1, y), "N"
case "|", "S":
return (x+1, y), "S"
case "-", "W":
return (x, y-1), "W"
case "-", "E":
return (x, y+1), "E"
case "L", "S":
return (x, y+1), "E"
case "L", "W":
return (x-1, y), "N"
case "7", "E":
return (x+1, y), "S"
case "7", "N":
return (x, y-1), "W"
case "J", "E":
return (x-1, y), "N"
case "J", "S":
return (x, y-1), "W"
def follow(start, grid, m, n):
loop = [start]
pos, direction = first_pos(start, grid, m, n)
while True:
print(pos)
pos, direction = next_pos(pos, grid, m, n, direction)
if pos == start:
break
else:
loop.append(pos)
return loop
with open(sys.argv[1]) as fh:
grid = [line.rstrip() for line in fh]
m, n = len(grid), len(grid[0])
for i, r in enumerate(grid):
if (j := r.find("S")) != -1:
break
start = (i, j)
loop = follow(start, grid, m, n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment