summaryrefslogtreecommitdiff
path: root/2024/aoc2024-d10.py
blob: 4f51a0d996a101cb78f68171eda847fbe0e7d617 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#advent of code 2024
#day 10
#tbh I don't think I even understood the task correctly 
#but the first idea for part 2 
#that came up to my head worked so i'll take it
#all I did was switch a set into a list 
#rewritten so the code does both parts now

grid = {};
xMin, yMin, xMax, yMax = 0,0,0,0;
dirs = [(1,0),(-1,0),(0,1),(0,-1)];
starts = [];

f = open("10.in","r");
for y,l in enumerate(f):
	yMax = max(y,yMax);
	for x,c in enumerate(l.strip()):
		grid[(x,y)]=int(c);
		if c == "0": starts.append((x,y));
		xMax = max(xMax,x);
f.close();		

def getAdjacent(pos,h):
	adj = [];
	xp, yp = pos;
	for i,d in enumerate(dirs):
		dx,dy = d;
		if grid.get((xp+dx,yp+dy),-1)-h == 1:
			adj.append((xp+dx,yp+dy,i));
	return adj;

def pathfinding(starts):
	score1 = 0;
	score2 = 0;
	for start in starts:
		subscore1 = set();
		subscore2 = list();
		x0,y0 = start;
		queue = [(x0,y0,0)];
		while queue:
			px,py,pd = queue.pop();
			CurrentHeight = grid.get((px,py),-1);
			if CurrentHeight == 9:
				subscore1.add((px,py));
				subscore2.append((px,py,pd));
			else:
				NextValid = getAdjacent((px,py),CurrentHeight);
				queue.extend(NextValid);
		score1 += len(subscore1);
		score2 += len(subscore2);
	return score1, score2;

part1, part2 = pathfinding(starts);
print("part 1 =", part1);
print("part 2 =", part2);