day12 - improved
This commit is contained in:
parent
4c3332a731
commit
cfe67b7889
38
day12.py
38
day12.py
@ -1,3 +1,4 @@
|
||||
from collections import deque
|
||||
from heapq import heappush, heappop
|
||||
from tools.aoc import AOCDay
|
||||
from tools.coordinate import Coordinate, DistanceAlgorithm
|
||||
@ -47,6 +48,32 @@ def get_dijkstra_path(height_map: Grid, start: Coordinate, end: Coordinate) -> i
|
||||
return steps
|
||||
|
||||
|
||||
def get_bfs_path(height_map: Grid, end: Coordinate) -> int:
|
||||
v = {end: None}
|
||||
q = deque()
|
||||
q.append(end)
|
||||
while q:
|
||||
cur = q.popleft()
|
||||
cur_v = height_map.get(cur)
|
||||
if cur_v == 0:
|
||||
end = cur
|
||||
break
|
||||
|
||||
for c in height_map.getNeighboursOf(cur, includeDiagonal=False):
|
||||
if c in v or height_map.get(c) + 1 < cur_v:
|
||||
continue
|
||||
|
||||
v[c] = cur
|
||||
q.append(c)
|
||||
|
||||
steps = 0
|
||||
while end in v:
|
||||
steps += 1
|
||||
end = v[end]
|
||||
|
||||
return steps
|
||||
|
||||
|
||||
class Day(AOCDay):
|
||||
inputs = [
|
||||
[
|
||||
@ -84,15 +111,8 @@ class Day(AOCDay):
|
||||
return get_dijkstra_path(*self.get_map())
|
||||
|
||||
def part2(self) -> Any:
|
||||
min_steps = float("inf")
|
||||
height_map, start, end = self.get_map()
|
||||
for c in height_map.getActiveCells():
|
||||
if height_map.get(c) == 0:
|
||||
steps_from_here = get_dijkstra_path(height_map, c, end)
|
||||
if steps_from_here is not None and steps_from_here + 1 < min_steps:
|
||||
min_steps = steps_from_here + 1
|
||||
|
||||
return min_steps - 1
|
||||
height_map, _, end = self.get_map()
|
||||
return get_bfs_path(height_map, end) - 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Loading…
Reference in New Issue
Block a user