|
| 1 | +advent_of_code::solution!(12); |
| 2 | + |
| 3 | +use advent_of_code::maneatingape::grid::*; |
| 4 | +use advent_of_code::maneatingape::point::*; |
| 5 | + |
| 6 | +fn parse_data(input: &str) -> Grid<u8> { |
| 7 | + Grid::parse(input) |
| 8 | +} |
| 9 | + |
| 10 | +fn find_data_with_flood(grid: &Grid<u8>) -> Vec<(usize, usize)> { |
| 11 | + let mut visited = grid.same_size_with(false); |
| 12 | + |
| 13 | + let mut result = vec![]; |
| 14 | + |
| 15 | + for y in 0..grid.height { |
| 16 | + for x in 0..grid.width { |
| 17 | + let start_location = Point::new(x, y); |
| 18 | + if visited[start_location] { |
| 19 | + continue; |
| 20 | + } |
| 21 | + |
| 22 | + let plot = grid[start_location]; |
| 23 | + |
| 24 | + let mut area = 0; |
| 25 | + let mut perimeter = 0; |
| 26 | + |
| 27 | + let mut queue = vec![start_location]; |
| 28 | + while let Some(position) = queue.pop() { |
| 29 | + if visited[position] { |
| 30 | + continue; |
| 31 | + } |
| 32 | + visited[position] = true; |
| 33 | + |
| 34 | + area += 1; |
| 35 | + perimeter += 4; |
| 36 | + |
| 37 | + for new_position in ORTHOGONAL.map(|o| position + o) { |
| 38 | + if grid.contains(new_position) && grid[new_position] == plot { |
| 39 | + queue.push(new_position); |
| 40 | + perimeter -= 1; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + result.push((area, perimeter)); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + result |
| 50 | +} |
| 51 | + |
| 52 | +pub fn part_one(input: &str) -> Option<u32> { |
| 53 | + let grid = parse_data(input); |
| 54 | + |
| 55 | + let result = find_data_with_flood(&grid) |
| 56 | + .into_iter() |
| 57 | + .map(|(area, perimeter)| (area * perimeter) as u32) |
| 58 | + .sum(); |
| 59 | + |
| 60 | + Some(result) |
| 61 | +} |
| 62 | + |
| 63 | +pub fn part_two(_input: &str) -> Option<u32> { |
| 64 | + None |
| 65 | +} |
| 66 | + |
| 67 | +#[cfg(test)] |
| 68 | +mod tests { |
| 69 | + use super::*; |
| 70 | + |
| 71 | + #[test] |
| 72 | + fn test_part_one() { |
| 73 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 74 | + assert_eq!(result, Some(1930)); |
| 75 | + } |
| 76 | + |
| 77 | + #[test] |
| 78 | + fn test_part_two() { |
| 79 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 80 | + assert_eq!(result, None); |
| 81 | + } |
| 82 | +} |
0 commit comments