day 10 optimizations
- reduce duplicate queue entries by not appending to the queue if a
point has a nonzero count. (if there's a count then it must have
already been queued.)
- use the correct data structure for a double-ended queue so pop(0) has
less work to do
- factor out the list of summits
of these three changes, only the last one has any noticable effect
on the run time. 🤷
main
parent
4634b831ea
commit
ad6279089f
14
day10/sol.py
14
day10/sol.py
|
@ -1,5 +1,5 @@
|
||||||
import itertools
|
import itertools
|
||||||
from collections import Counter
|
from collections import Counter, deque
|
||||||
def read(file):
|
def read(file):
|
||||||
return [line.strip() for line in file]
|
return [line.strip() for line in file]
|
||||||
|
|
||||||
|
@ -18,20 +18,22 @@ def solve(file):
|
||||||
c = get(x,y)
|
c = get(x,y)
|
||||||
if c == h:
|
if c == h:
|
||||||
assert (x,y) not in done
|
assert (x,y) not in done
|
||||||
queue.append((x,y))
|
if (x,y) not in count:
|
||||||
|
queue.append((x,y))
|
||||||
count[x,y] += n
|
count[x,y] += n
|
||||||
|
|
||||||
trailheads = [(x,y) for x,y in points() if get(x,y) == '0']
|
trailheads = [(x,y) for x,y in points() if get(x,y) == '0']
|
||||||
|
summits = [(x,y) for x,y in points() if get(x,y) == '9']
|
||||||
|
|
||||||
t1 = 0
|
t1 = 0
|
||||||
t2 = 0
|
t2 = 0
|
||||||
for p in trailheads:
|
for p in trailheads:
|
||||||
queue = [p]
|
queue = deque([p])
|
||||||
done = set()
|
done = set()
|
||||||
count = Counter()
|
count = Counter()
|
||||||
count[p] = 1
|
count[p] = 1
|
||||||
while queue:
|
while queue:
|
||||||
x,y = queue.pop(0)
|
x,y = queue.popleft()
|
||||||
#print(x,y,queue)
|
#print(x,y,queue)
|
||||||
if (x,y) in done:
|
if (x,y) in done:
|
||||||
continue
|
continue
|
||||||
|
@ -44,8 +46,8 @@ def solve(file):
|
||||||
visit(x-1,y,h,n)
|
visit(x-1,y,h,n)
|
||||||
visit(x,y+1,h,n)
|
visit(x,y+1,h,n)
|
||||||
visit(x,y-1,h,n)
|
visit(x,y-1,h,n)
|
||||||
for x,y in points():
|
for x,y in summits:
|
||||||
if get(x,y) == '9' and (x,y) in done:
|
if (x,y) in done:
|
||||||
t1 += 1
|
t1 += 1
|
||||||
t2 += count[x,y]
|
t2 += count[x,y]
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue