aoc/year2022/day18.rs
1//! # Boiling Boulders
2//!
3//! The lava droplet is a fixed size so we can use a one dimensional fixed size array to store the
4//! cube data for speed.
5//!
6//! For part two we use the [flood fill](https://en.wikipedia.org/wiki/Flood_fill) algorithm
7//! starting from any corner to fill the outside space with water. We then use the same exposed
8//! edge counting approach as part one, but only considering faces that touch a water drop.
9use crate::util::iter::*;
10use crate::util::parse::*;
11
12const SIZE: usize = 24;
13
14pub fn parse(input: &str) -> Vec<u8> {
15 let mut cube = vec![0; SIZE * SIZE * SIZE];
16 // Leave a 1 layer boundary around the outside for the part two flood fill
17 // and also so that we don't have to use boundary checks when checking neighbors.
18 input.iter_unsigned().chunk::<3>().for_each(|[x, y, z]: [usize; 3]| {
19 cube[(x + 1) * SIZE * SIZE + (y + 1) * SIZE + (z + 1)] = 1;
20 });
21 cube
22}
23
24pub fn part1(input: &[u8]) -> u32 {
25 // The exposed surface area is the 6 faces of the cubes minus any neighbors.
26 count(input, |x| 6 - x)
27}
28
29pub fn part2(input: &[u8]) -> u32 {
30 // "Paint" the outside of the cube with water drops.
31 // Use 8 as the nearest power of two greater than 6.
32 let mut cube = input.to_vec();
33 cube[0] = 8;
34
35 let mut todo = Vec::new();
36 todo.push(0);
37
38 while let Some(index) = todo.pop() {
39 let mut flood_fill = |next| {
40 if next < input.len() && cube[next] == 0 {
41 cube[next] = 8;
42 todo.push(next);
43 }
44 };
45
46 // We may wrap around but that index will be out of bounds.
47 flood_fill(index.wrapping_sub(1));
48 flood_fill(index + 1);
49 flood_fill(index.wrapping_sub(SIZE));
50 flood_fill(index + SIZE);
51 flood_fill(index.wrapping_sub(SIZE * SIZE));
52 flood_fill(index + SIZE * SIZE);
53 }
54
55 // Divide by 8 so that we only count water cubes.
56 count(&cube, |x| x >> 3)
57}
58
59fn count(cube: &[u8], adjust: fn(u32) -> u32) -> u32 {
60 let mut total = 0;
61
62 for i in 0..cube.len() {
63 if cube[i] == 1 {
64 // No need for boundary checks as all cubes are at least 1 away from the edge.
65 total += adjust(
66 (cube[i - 1]
67 + cube[i + 1]
68 + cube[i - SIZE]
69 + cube[i + SIZE]
70 + cube[i - SIZE * SIZE]
71 + cube[i + SIZE * SIZE]) as u32,
72 );
73 }
74 }
75
76 total
77}