diff --git a/lib/day23.rb b/lib/day23.rb index 86c0149..e5acad1 100644 --- a/lib/day23.rb +++ b/lib/day23.rb @@ -14,6 +14,40 @@ def find_longest_path @current_longest end + def longest_path_queue + queue = Queue.new + queue << [@start, Set.new([@start]), [@start]] + + until queue.empty? + current, visited, path = queue.pop + + if current == @goal && path.length > @current_longest + @current_longest = path.length - 1 + else + next_positions = case [@forest_map[current], @dry] + when [:right, false] + [[current[0] + 1, current[1]]] + when [:down, false] + [[current[0], current[1] + 1]] + else + neighbors(current) + end + + next_positions.each do |next_pos| + next unless @forest_map.key?(next_pos) && !visited.include?(next_pos) && @forest_map[next_pos] != :tree + + new_visited = visited.dup + new_visited.add(next_pos) + new_path = path.dup + new_path << next_pos + queue << [next_pos, new_visited, new_path] + end + end + end + + @current_longest + end + private def dfs(current, visited, path) @@ -79,4 +113,11 @@ def part1 forest = Forest.new(@maze, start, goal) forest.find_longest_path end + + def part2 + start = find(:start) + goal = find(:end) + forest = Forest.new(@maze, start, goal) + forest.longest_path_queue + end end diff --git a/test/unit/day23_test.rb b/test/unit/day23_test.rb index cd4d51d..9a32a27 100644 --- a/test/unit/day23_test.rb +++ b/test/unit/day23_test.rb @@ -8,9 +8,21 @@ def test_day23a assert_equal(94, sut.part1) end + def test_day23b + sut = Day23.new + sut.load('data/day23a.txt') + assert_equal(154, sut.part2) + end + def test_day23a_part1 sut = Day23.new sut.load('data/day23.txt') assert_equal(2430, sut.part1) end + + def _test_day23a_part2 + sut = Day23.new + sut.load('data/day23.txt') + assert_equal(0, sut.part2) + end end