11class Day12
22 def part_one ( input )
3+ Day12Part1 . new . part_one ( input )
4+ end
5+
6+ def part_two ( input )
7+ Day12Part2 . new . part_two ( input )
8+ end
9+ end
10+
11+ class Day12Part2
12+ def part_two ( input )
313 @map = input . split ( "\n " )
414 @rows = @map . length
515 @cols = @map [ 0 ] . length
@@ -8,8 +18,67 @@ def part_one(input)
818 total_price
919 end
1020
11- def part_two ( input )
12- 0
21+ def total_price
22+ regions = find_regions
23+ regions . sum { |region | region [ :area ] * region [ :perimeter ] }
24+ end
25+
26+ def find_regions
27+ regions = [ ]
28+ ( 0 ...@rows ) . each do |row |
29+ ( 0 ...@cols ) . each do |col |
30+ next if @visited [ row ] [ col ]
31+
32+ char = @map [ row ] [ col ]
33+ area , perimeter = explore_region ( row , col , char )
34+ regions << { area : area , perimeter : perimeter }
35+ end
36+ end
37+ regions
38+ end
39+
40+ def explore_region ( row , col , char )
41+ queue = [ [ row , col ] ]
42+ area = 0
43+ perimeter = 0
44+
45+ until queue . empty?
46+ current_row , current_col = queue . shift
47+ next if out_of_bounds? ( current_row , current_col ) || @visited [ current_row ] [ current_col ]
48+
49+ next unless @map [ current_row ] [ current_col ] == char
50+
51+ @visited [ current_row ] [ current_col ] = true
52+ area += 1
53+
54+ # Check all four directions
55+ [ [ 0 , 1 ] , [ 1 , 0 ] , [ 0 , -1 ] , [ -1 , 0 ] ] . each do |dr , dc |
56+ new_row = current_row + dr
57+ new_col = current_col + dc
58+ if out_of_bounds? ( new_row , new_col ) || @map [ new_row ] [ new_col ] != char
59+ perimeter += 1
60+ else
61+ queue << [ new_row , new_col ] unless @visited [ new_row ] [ new_col ]
62+ end
63+ end
64+ end
65+
66+ [ area , perimeter ]
67+ end
68+
69+ def out_of_bounds? ( row , col )
70+ row < 0 || row >= @rows || col < 0 || col >= @cols
71+ end
72+ end
73+
74+ class Day12Part1
75+ def part_one ( input )
76+ @map = input . split ( "\n " )
77+ @rows = @map . length
78+ @cols = @map [ 0 ] . length
79+ @visited = Array . new ( @rows ) { Array . new ( @cols , false ) }
80+
81+ total_price
1382 end
1483
1584 def total_price
0 commit comments