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.
70 lines
1.6 KiB
70 lines
1.6 KiB
#!/usr/bin/env python3
|
|
|
|
import sys
|
|
|
|
def risk_level(m, x, y):
|
|
adj = []
|
|
if x-1 > -1:
|
|
adj.append(m[x-1][y])
|
|
try: adj.append(m[x+1][y])
|
|
except IndexError: pass
|
|
if y-1 > -1:
|
|
adj.append(m[x][y-1])
|
|
try: adj.append(m[x][y+1])
|
|
except IndexError: pass
|
|
|
|
for a in adj:
|
|
if a <= m[x][y]:
|
|
return 0
|
|
return m[x][y] + 1
|
|
|
|
def basin(m, x, y):
|
|
while (x,y) not in bas:
|
|
adj = {}
|
|
adj[(0,0)] = m[x][y]
|
|
if x-1 > -1:
|
|
adj[(-1,0)] = m[x-1][y]
|
|
try: adj[(1,0)] = m[x+1][y]
|
|
except IndexError: pass
|
|
if y-1 > -1:
|
|
adj[(0,-1)] = m[x][y-1]
|
|
try: adj[(0,1)] = m[x][y+1]
|
|
except IndexError: pass
|
|
|
|
mi = min(adj.items(),key=lambda x: x[1])
|
|
|
|
x += mi[0][0]
|
|
y += mi[0][1]
|
|
bas[(x,y)] += 1
|
|
|
|
|
|
if __name__ == '__main__':
|
|
lines = open(sys.argv[1]).read().strip('\n\n').split('\n') # or split \n\n or sth similar
|
|
mp = [[int(i) for i in l] for l in lines]
|
|
|
|
bas = {}
|
|
risk = 0
|
|
for x in range(len(mp)):
|
|
for y in range(len(mp[0])):
|
|
r = risk_level(mp, x, y)
|
|
risk += r
|
|
if r > 0:
|
|
bas[(x,y)] = 0
|
|
|
|
|
|
for x in range(len(mp)):
|
|
for y in range(len(mp[0])):
|
|
if mp[x][y] != 9:
|
|
basin(mp, x, y)
|
|
|
|
b = sorted(bas.values(), reverse=True)
|
|
|
|
# challenge 1
|
|
res1 = str(risk)
|
|
print("challenge 1:" +"\n" + res1 + "\n")
|
|
|
|
# challenge 2
|
|
|
|
res2 = str(b[0]*b[1]*b[2])
|
|
print("challenge 2:" +"\n" + res2 + "\n")
|
|
|
|
|