@@ -18,34 +18,32 @@ class TopoMap {
18
18
19
19
def get (Vec2 pos ) { values[pos. y][pos. x] }
20
20
21
- def traceTrail (Vec2 pos , boolean isPart1 , Set<Vec2 > visited = new HashSet () ) {
22
- if (isPart1 ) {
21
+ def traceTrail (Vec2 pos , Set<Vec2 > visited ) {
22
+ if (visited != null ) {
23
23
if (pos in visited) {
24
- return
24
+ return 0
25
25
}
26
-
27
26
visited. add(pos)
28
27
}
29
28
30
29
int value = get(pos)
30
+ int score = 0
31
31
if (value == 0 ) {
32
- if (isPart1) {
33
- part1++
34
- } else {
35
- part2++
36
- }
32
+ score++
37
33
}
38
34
39
35
for (int dy in (-1 .. 1 )) {
40
36
for (int dx in (-1 .. 1 )) {
41
37
if (dy == 0 ^ dx == 0 ) {
42
38
Vec2 neigh = new Vec2 (pos. x + dx, pos. y + dy)
43
39
if (neigh. y >= 0 && neigh. y < height && neigh. x >= 0 && neigh. x < width && get(neigh) == value - 1 ) {
44
- traceTrail(neigh, isPart1 , visited)
40
+ score + = traceTrail(neigh, visited)
45
41
}
46
42
}
47
43
}
48
44
}
45
+
46
+ return score
49
47
}
50
48
}
51
49
@@ -54,23 +52,21 @@ if (args.length == 0) {
54
52
System . exit(1 )
55
53
}
56
54
57
- List<List<Integer > > values = new File (args[0 ]). text
58
- .lines()
59
- .map { it. chars(). map { it - (int ) ' 0' }. toList() }
60
- .toList()
61
-
55
+ List<List<Integer > > values = new File (args[0 ]). text. lines(). map { it. chars(). map { it - (int ) ' 0' }. toList() }. toList()
62
56
TopoMap topoMap = new TopoMap (values)
63
57
58
+ int part1 = 0
59
+ int part2 = 0
60
+
64
61
for (int y in 0 .. < topoMap. height) {
65
62
for (int x in 0 .. < topoMap. width) {
66
63
Vec2 pos = new Vec2 (x, y)
67
64
if (topoMap. get(pos) == 9 ) {
68
- for (boolean isPart1 in [true , false ]) {
69
- topoMap. traceTrail(pos, isPart1)
70
- }
65
+ part1 + = topoMap. traceTrail(pos, new HashSet ())
66
+ part2 + = topoMap. traceTrail(pos, null )
71
67
}
72
68
}
73
69
}
74
70
75
- println " Part 1: $t opoMap . part1 "
76
- println " Part 2: $t opoMap . part2 "
71
+ println " Part 1: $part1 "
72
+ println " Part 2: $part2 "
0 commit comments