25_cucumbers.py 702 B

12345678910111213141516171819202122232425262728
  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. def right(i):
  7. y, x = divmod(i, w)
  8. return y * w + (x + 1) % w
  9. def down(i):
  10. return (i + w) % len(grid)
  11. def move_axis(match, forward):
  12. can_move = [src for src, cell in enumerate(grid)
  13. if cell == match and grid[forward(src)] == '.']
  14. for src in can_move:
  15. grid[forward(src)] = match
  16. grid[src] = '.'
  17. return bool(can_move)
  18. step = 1
  19. while move_axis('>', right) | move_axis('v', down):
  20. step += 1
  21. return step
  22. print(move(*parse(sys.stdin.read())))