day14 - p2 faster

This commit is contained in:
Stefan Harmuth 2022-12-14 10:41:31 +01:00
parent 4c3332a731
commit d5a59a80f5

View File

@ -1,3 +1,4 @@
from collections import deque
from enum import Enum from enum import Enum
from tools.aoc import AOCDay from tools.aoc import AOCDay
from tools.coordinate import Coordinate from tools.coordinate import Coordinate
@ -65,23 +66,19 @@ class Day(AOCDay):
def part2(self) -> Any: def part2(self) -> Any:
cave = self.get_cave() cave = self.get_cave()
y = cave.maxY + 2 v = set()
for x in range(cave.minX - 200, cave.maxX + 200): q = deque()
cave.set(Coordinate(x, y), TType.ROCK) q.append(SAND_SOURCE)
while q:
current = q.pop()
if current in v or current.y > cave.maxY + 1:
continue
v.add(current)
for c in [Coordinate(current.x, current.y + 1), Coordinate(current.x - 1, current.y + 1), Coordinate(current.x + 1, current.y + 1)]:
if cave.get(c) == TType.AIR:
q.append(c)
while cave.get(SAND_SOURCE) == TType.AIR: return len(v)
tx, ty = 0, 0
while ty <= cave.maxY:
ty += 1
for c in [Coordinate(tx, ty), Coordinate(tx - 1, ty), Coordinate(tx + 1, ty)]:
if cave.get(SAND_SOURCE + c) == TType.AIR:
tx += compare(c.x, tx)
break
else:
cave.set(SAND_SOURCE + Coordinate(tx, ty - 1), TType.SAND)
break
return cave.count(TType.SAND)
if __name__ == '__main__': if __name__ == '__main__':