You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 satır
2.1KB

  1. def render(graph, default='.'):
  2. xmin, *_, xmax = sorted(int(p.real) for p in walls)
  3. ymin, *_, ymax = sorted(int(p.imag) for p in walls)
  4. out = ''
  5. for y in range(ymin, ymax + 1):
  6. for x in range(xmin, xmax + 1):
  7. out += graph.get(complex(x, y), default)
  8. out += '\n'
  9. return out
  10. def connected_components(graph):
  11. groups = []
  12. while graph:
  13. seen = set()
  14. edge = {graph.pop()}
  15. while edge:
  16. seen |= edge
  17. edge = {pp + ss for pp in edge for ss in [1, -1, 1j, -1j]} & graph - seen
  18. groups.append(seen)
  19. graph -= seen
  20. return groups
  21. text = open(0).read()
  22. p2 = True
  23. walls = {0}
  24. pos = 0
  25. for line in text.splitlines():
  26. d, n, rest = line.split()
  27. if p2:
  28. n, d = int(rest[1:-1][1:][:5], 16), 'RDLU'[int(rest[-2])]
  29. pos += {'R': 1, 'D': 1j, 'L': -1, 'U': -1j}[d] * int(n)
  30. walls.add(pos)
  31. b2s = {
  32. complex(bx, by) + dx + dy: 3 * complex(sx, sy) + dx + dy
  33. for sx, bx in enumerate(sorted({p.real for p in walls}))
  34. for sy, by in enumerate(sorted({p.imag for p in walls}))
  35. for dx in [-1, 0, 1] for dy in [-1j, 0, 1j]
  36. }
  37. pos, smallpos = next(iter(b2s.items()))
  38. walls = {smallpos}
  39. for line in text.splitlines():
  40. d, n, rest = line.split()
  41. if p2:
  42. n, d = int(rest[1:-1][1:][:5], 16), 'RDLU'[int(rest[-2])]
  43. dirx = {'R': 1, 'D': 1j, 'L': -1, 'U': -1j}[d]
  44. pos += dirx * int(n)
  45. goal = b2s[pos]
  46. while smallpos != goal:
  47. smallpos += dirx
  48. walls.add(smallpos)
  49. xmin, *_, xmax = sorted(int(p.real) for p in b2s.values())
  50. ymin, *_, ymax = sorted(int(p.imag) for p in b2s.values())
  51. void = {complex(x, y) for x in range(xmin, xmax + 1) for y in range(ymin, ymax + 1)} - walls
  52. groups = connected_components(void)
  53. inside = {p for g in groups if not any(p.real in {xmin, xmax} or p.imag in {ymin, ymax} for p in g) for p in g}
  54. solid = inside | walls
  55. # print(render({k: '#' for k in solid}))
  56. s2b = {v: k for k, v in b2s.items()}
  57. out = 0
  58. for smallpos in solid:
  59. c1, c2 = s2b[smallpos], s2b[smallpos + 1 + 1j]
  60. w, h = (c2 - c1).real, (c2 - c1).imag
  61. out += int(w * h)
  62. print(out)