Skip to main content

aoc/year2023/
day22.rs

1//! # Sand Slabs
2//!
3//! Inspecting the input provides a useful insight. The x and y coordinates of bricks are
4//! restricted to between 0 and 9 inclusive so the final shape of the pile will resemble a tall
5//! narrow tower similar to a [Jenga game](https://en.wikipedia.org/wiki/Jenga).
6//!
7//! A second insight is that this is a graph problem in disguise. Sorting the bricks in ascending
8//! z order is equivalent to a [topological sort](https://en.wikipedia.org/wiki/Topological_sorting)
9//! where each brick is a node and a directed edge links bricks that support other bricks.
10//!
11//! By iterating over each brick in order its final resting location and supporting bricks can be
12//! calculated immediately. For example, taking the first 3 example bricks:
13//!
14//! ```none
15//! Brick               Heights    Indices
16//!
17//! 1,0,1~1,2,1 <- A    0 1 0      X 0 X    Already in final position
18//!                     0 1 0      X 0 X
19//!                     0 1 0      X 0 X
20//!
21//! 0,0,2~2,0,2 <- B    2 2 2      1 1 1    Already in final position
22//!                     0 1 0      X 0 X
23//!                     0 1 0      X 0 X
24//!
25//! 0,2,3~2,2,3 <- C    2 2 2      1 1 1    Moves downwards by 1
26//!                     0 1 0      X 0 X
27//!                     2 2 2      2 2 2
28//! ```
29//!
30//! ## Part One
31//!
32//! If a brick is supported by only a single brick then the parent brick cannot be safely removed
33//! so we mark it as unsafe. Multiple bricks could potentially be independently supported by a
34//! single parent brick so using a boolean flag means that we won't overcount.
35//!
36//! ## Part Two
37//!
38//! Unsafe bricks are a [dominator](https://en.wikipedia.org/wiki/Dominator_(graph_theory)) in
39//! graph theory as every path from the root (floor) to bricks supported by them must pass through
40//! the unsafe node.
41//!
42//! To count the total number of bricks that fall when all unsafe bricks are removed one at a time
43//! we build a linked list of bricks as we iterate through the nodes. Each brick has a `depth`
44//! which is the number of unsafe "dominator" nodes that connect it to the root. For example:
45//!
46//! ```none
47//! Depth   0     1     2     1     0
48//!       | A ┬-> B --> C ┬-> D ┬-> E
49//!       |   |           |     |
50//! Floor |   └-> F ------┘     |
51//!       | G ------------------┘
52//! ```
53//!
54//! * `A` and `G` rest on the floor so their depth is 0 as they can never fall.
55//! * `B` and `F` are both supported only by `A` so their depth is 1.
56//! * `C` will fall if either `A` or `B` is removed so its depth is 2.
57//! * `D` will only fall when `A` is removed. Removing `F` would leave it supported by `B` and `C`
58//!   or vice-versa. The common ancestor of the path to the root is `A` so its depth is 1.
59//! * `E`'s common ancestor is the floor so its depth is 0.
60//!
61//! In total `0 (A) + 0 (G) + 1 (B) + 1 (F) + 2 (C) + 1 (D) + 0 (E) = 5` bricks will fall.
62use crate::util::iter::*;
63use crate::util::parse::*;
64
65type Input = (usize, usize);
66
67pub fn parse(input: &str) -> Input {
68    // Parse each brick into an array of 6 elements, one for each coordinate.
69    let mut bricks: Vec<_> = input.iter_unsigned::<usize>().chunk::<6>().collect();
70    // x and y are limited to 10 in each direction so we can use a fixed-size array.
71    let mut heights = [0; 100];
72    let mut indices = [usize::MAX; 100];
73
74    // Calculate the answer to both parts simultaneously for efficiency.
75    let mut safe = vec![true; bricks.len()];
76    let mut dominator: Vec<(usize, usize)> = Vec::with_capacity(bricks.len());
77
78    // Sort ascending by lowest z coordinate.
79    bricks.sort_unstable_by_key(|b| b[2]);
80
81    for (i, &[x1, y1, z1, x2, y2, z2]) in bricks.iter().enumerate() {
82        // Treat the 1D array as a 2D grid.
83        let start = 10 * y1 + x1;
84        let end = 10 * y2 + x2;
85        let step = if y2 > y1 { 10 } else { 1 };
86        let height = z2 - z1 + 1;
87
88        // Find the highest z coordinate underneath the brick looking downwards along the z axis
89        // so only considering x and y coordinates.
90        let top = (start..end + 1).step_by(step).map(|j| heights[j]).max().unwrap();
91
92        // Track what's underneath the brick.
93        let mut previous = usize::MAX;
94        let mut underneath = 0;
95        let mut parent = 0;
96        let mut depth = 0;
97
98        for j in (start..end + 1).step_by(step) {
99            if heights[j] == top {
100                let index = indices[j];
101                if index != previous {
102                    previous = index;
103                    underneath += 1;
104
105                    if underneath == 1 {
106                        (parent, depth) = dominator[previous];
107                    } else {
108                        // Find common ancestor.
109                        let (mut a, mut b) = (parent, depth);
110                        let (mut x, mut y) = dominator[previous];
111
112                        // The depth must be the same.
113                        while b > y {
114                            (a, b) = dominator[a];
115                        }
116                        while y > b {
117                            (x, y) = dominator[x];
118                        }
119
120                        // Bricks at the same depth could still have different paths from the
121                        // root so we need to also check the indices match.
122                        while a != x {
123                            (a, b) = dominator[a];
124                            (x, _) = dominator[x];
125                        }
126
127                        (parent, depth) = (a, b);
128                    }
129                }
130            }
131
132            // Update the x-y grid underneath the brick with the new highest point and index.
133            heights[j] = top + height;
134            indices[j] = i;
135        }
136
137        // Increase depth by one for each dominator node in the path from the root.
138        if underneath == 1 {
139            safe[previous] = false;
140            parent = previous;
141            depth = dominator[previous].1 + 1;
142        }
143
144        dominator.push((parent, depth));
145    }
146
147    let part_one = safe.iter().filter(|&&b| b).count();
148    let part_two = dominator.iter().map(|&(_, d)| d).sum();
149    (part_one, part_two)
150}
151
152pub fn part1(input: &Input) -> usize {
153    input.0
154}
155
156pub fn part2(input: &Input) -> usize {
157    input.1
158}