25_cucumbers.py 754 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/env python3
  2. import sys
  3. def parse(content):
  4. return list(content.replace('\n', '')), content.find('\n')
  5. def move(grid, w):
  6. h = len(grid) // w
  7. def right(i):
  8. y, x = divmod(i, w)
  9. return y * w + (x + 1) % w
  10. def down(i):
  11. y, x = divmod(i, w)
  12. return (y + 1) % h * w + x
  13. def move_axis(match, forward):
  14. can_move = [src for src, cell in enumerate(grid)
  15. if cell == match and grid[forward(src)] == '.']
  16. for src in can_move:
  17. grid[forward(src)] = match
  18. grid[src] = '.'
  19. return bool(can_move)
  20. step = 1
  21. while move_axis('>', right) | move_axis('v', down):
  22. step += 1
  23. return step
  24. print(move(*parse(sys.stdin.read())))