Skip to content

Commit 26aa166

Browse files
committed
Day 10 - Puzzle 2
1 parent a8d694e commit 26aa166

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

β€Žlib/solutions/day_10.rbβ€Ž

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ def part_one(input)
55
end
66

77
def part_two(input)
8-
0
8+
thf = TrailheadFinder.new(input)
9+
thf.find_trailheads_with_rating
910
end
1011
end
1112

@@ -58,4 +59,39 @@ def count_reachable_nines(x, y)
5859

5960
reachable_nines
6061
end
62+
63+
def find_trailheads_with_rating
64+
total_paths = 0
65+
66+
@grid.each_with_index do |row, y|
67+
row.each_with_index do |cell, x|
68+
total_paths += count_unique_paths(x, y) if cell == 0
69+
end
70+
end
71+
72+
total_paths
73+
end
74+
75+
def count_unique_paths(x, y)
76+
visited = Array.new(@h) { Array.new(@w, false) }
77+
paths = 0
78+
79+
dfs(x, y, 0, visited, paths)
80+
end
81+
82+
def dfs(x, y, current_value, visited, paths)
83+
return 0 if x < 0 || x >= @w || y < 0 || y >= @h || visited[y][x] || @grid[y][x] != current_value
84+
85+
return 1 if @grid[y][x] == 9
86+
87+
visited[y][x] = true
88+
path_count = 0
89+
90+
[[0, 1], [1, 0], [0, -1], [-1, 0]].each do |dx, dy|
91+
path_count += dfs(x + dx, y + dy, current_value + 1, visited, paths)
92+
end
93+
94+
visited[y][x] = false
95+
path_count
96+
end
6197
end

β€Žspec/solutions/day_10_spec.rbβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
describe '#part_two' do
2424
it 'calculates the correct solutions for part two' do
25-
expect(subject.part_two(input)).to eq(0)
25+
expect(subject.part_two(input)).to eq(81)
2626
end
2727
end
2828
end

0 commit comments

Comments
Β (0)