-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.jl
88 lines (83 loc) · 2.12 KB
/
day9.jl
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
tdata = readlines("test9.txt")
##
function sum_risk(data)
risk = 0
for (y, row) in enumerate(data)
for (x, ch) in enumerate(row)
if x > 1 && row[x-1] <= ch
continue
elseif x < length(row) && row[x+1] <= ch
continue
elseif y > 1 && data[y-1][x] <= ch
continue
elseif y < length(data) && data[y+1][x] <= ch
continue
end
risk += ch - '0' + 1
end
end
risk
end
##
sum_risk(tdata)
##
data = readlines("input9.txt")
sum_risk(data)
##
function basin_sizes(data)
lowpoints = []
for (y, row) in enumerate(data)
for (x, ch) in enumerate(row)
if x > 1 && row[x-1] <= ch
continue
elseif x < length(row) && row[x+1] <= ch
continue
elseif y > 1 && data[y-1][x] <= ch
continue
elseif y < length(data) && data[y+1][x] <= ch
continue
end
push!(lowpoints, (x,y))
end
end
bsz = []
for start in lowpoints
basin = Set()
stack = [start]
while length(stack) > 0
(x,y) = pop!(stack)
push!(basin,(x,y))
ch = data[y][x]
if x > 1
cand = data[y][x-1]
if cand > ch && cand < '9'
push!(stack, (x-1,y))
end
end
if x < length(data[1])
cand = data[y][x+1]
if cand > ch && cand < '9'
push!(stack, (x+1,y))
end
end
if y > 1
cand = data[y-1][x]
if cand > ch && cand < '9'
push!(stack, (x,y-1))
end
end
if y < length(data)
cand = data[y+1][x]
if cand > ch && cand < '9'
push!(stack, (x,y+1))
end
end
end
push!(bsz, length(basin))
end
prod(sort(bsz)[end-2:end])
end
##
basin_sizes(tdata)
##
basin_sizes(data)