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 = 22;
13
14pub fn parse(input: &str) -> Vec<u32> {
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: &[u32]) -> 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: &[u32]) -> u32 {
30    let mut cube = input.to_vec();
31    // "Paint" the outside of the cube with water drops.
32    flood_fill(&mut cube, 0);
33    // Divide by 8 so that we only count water cubes.
34    count(&cube, |x| x >> 3)
35}
36
37fn count(cube: &[u32], adjust: fn(u32) -> u32) -> u32 {
38    let mut total = 0;
39
40    for i in 0..cube.len() {
41        if cube[i] == 1 {
42            // No need for boundary checks as all cubes are at least 1 away from the edge.
43            total += adjust(
44                cube[i - 1]
45                    + cube[i + 1]
46                    + cube[i - SIZE]
47                    + cube[i + SIZE]
48                    + cube[i - SIZE * SIZE]
49                    + cube[i + SIZE * SIZE],
50            );
51        }
52    }
53
54    total
55}
56
57fn flood_fill(cube: &mut [u32], i: usize) {
58    if cube.get(i) == Some(&0) {
59        // Use 8 as the nearest power of two greater than 6.
60        cube[i] = 8;
61        // We may wrap around to an opposite edge but that will also be water.
62        flood_fill(cube, i.saturating_sub(1));
63        flood_fill(cube, i + 1);
64        flood_fill(cube, i.saturating_sub(SIZE));
65        flood_fill(cube, i + SIZE);
66        flood_fill(cube, i.saturating_sub(SIZE * SIZE));
67        flood_fill(cube, i + SIZE * SIZE);
68    }
69}