14_sand.py 989 B

12345678910111213141516171819202122232425262728293031323334
  1. #!/usr/bin/env python3
  2. import sys
  3. def parse(f):
  4. for line in f:
  5. path = [tuple(map(int, xy.split(','))) for xy in line.split(' -> ')]
  6. for i in range(len(path) - 1):
  7. (xs, ys), (xe, ye) = sorted(path[i:i + 2])
  8. for x in range(xs, xe + 1):
  9. for y in range(ys, ye + 1):
  10. yield x, y
  11. def fill(obstacles, bottom, void):
  12. def drop():
  13. x = 500
  14. for y in range(void):
  15. for dx in (0, -1, 1):
  16. if (x + dx, y + 1) not in obstacles and y + 1 != bottom:
  17. x += dx
  18. break
  19. else:
  20. return x, y
  21. pos = drop()
  22. while pos and pos != (500, 0):
  23. obstacles.add(pos)
  24. pos = drop()
  25. return len(obstacles)
  26. obstacles = set(parse(sys.stdin))
  27. rock = len(obstacles)
  28. bottom = max(y for x, y in obstacles) + 2
  29. print(fill(obstacles, bottom, bottom - 1) - rock)
  30. print(fill(obstacles, bottom, bottom + 1) - rock + 1)