1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use crate::input::Input;
#[cfg(feature = "visualization")]
use crate::painter::PainterRef;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};

const DIRECTIONS: &[(i32, i32); 4] = &[(0, 1), (0, -1), (-1, 0), (1, 0)];

#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
struct Key {
    value: u8,
}

/// Keys represented as a bit mask where bit 0 is set for 'a', bit 1 is set for 'b' and so on.
type KeyBitset = u32;

impl Key {
    const fn new(value: u8) -> Self {
        Self { value }
    }

    const fn bit_mask(self) -> KeyBitset {
        1 << (self.value as usize - 'a' as usize)
    }
}

/// Path between keys (or from starting position to a key).
struct Edge {
    /// The key at the other end.
    target_key: Key,
    /// Required steps to reach the target key.
    steps: usize,
    /// The keys needed to traverse this path.
    needed_keys: KeyBitset,
    #[cfg(feature = "visualization")]
    x: i32,
    #[cfg(feature = "visualization")]
    y: i32,
}

pub fn steps_to_gather_all_keys(
    input_string: &str,
    #[cfg(feature = "visualization")] mut painter: &mut PainterRef,
    #[cfg(feature = "visualization")] map_x_offset: usize,
    #[cfg(feature = "visualization")] map_y_offset: usize,
    #[cfg(feature = "visualization")] mut global_cols: usize,
    #[cfg(feature = "visualization")] mut global_rows: usize,
) -> Result<usize, String> {
    #[cfg(feature = "visualization")]
    painter.fill_style_rgb(255, 0, 0);

    let rows = input_string.lines().count();
    let cols = input_string.lines().next().ok_or("Empty input")?.len();
    let mut map = vec![b'#'; rows * cols];
    let mut found_keys = HashMap::new();
    let mut all_keys_bitset = 0 as KeyBitset;

    let index_of = |x, y| x + y * cols;

    #[cfg(feature = "visualization")]
    {
        if global_rows == 0 {
            global_rows = rows;
            global_cols = cols;
        }
    }

    for (y, line) in input_string.lines().enumerate() {
        if line.len() != cols {
            return Err("Not all rows have same width".to_string());
        }
        line.chars().enumerate().for_each(|(x, c)| {
            let byte = c as u8;
            let current_position = (x as i32, y as i32);

            #[cfg(feature = "visualization")]
            let canvas_x = (x + map_x_offset) as f64 / global_cols as f64;
            #[cfg(feature = "visualization")]
            let canvas_y = (y + map_y_offset) as f64 / global_rows as f64;
            #[cfg(feature = "visualization")]
            let draw_width = 0.95 / global_cols as f64;
            #[cfg(feature = "visualization")]
            let draw_height = 0.95 / global_rows as f64;
            #[cfg(feature = "visualization")]
            let draw = |drawer: &mut PainterRef| {
                drawer.fill_rect(canvas_x, canvas_y, draw_width, draw_height);
            };

            let char_to_insert = match c {
                '@' => {
                    // The single entrance.
                    found_keys.insert(Key::new(b'@'), current_position);
                    #[cfg(feature = "visualization")]
                    {
                        painter.fill_style_rgb(0, 0, 255);
                        draw(&mut painter);
                    }
                    b'.'
                }
                'a'..='z' => {
                    // A key.
                    let found_key = Key::new(byte);
                    all_keys_bitset |= found_key.bit_mask();
                    found_keys.insert(found_key, current_position);
                    #[cfg(feature = "visualization")]
                    {
                        painter.fill_style_rgb(0, 255, 0);
                        draw(&mut painter);
                    }
                    byte
                }
                '#' => {
                    #[cfg(feature = "visualization")]
                    {
                        painter.fill_style_rgb(255, 0, 0);
                        draw(&mut painter);
                    }
                    // Stone wall.
                    return;
                }
                _ => {
                    #[cfg(feature = "visualization")]
                    {
                        if ('A'..='Z').contains(&c) {
                            painter.fill_style_rgb(0, 255, 255);
                            draw(&mut painter);
                        }
                    }
                    byte
                }
            };
            map[index_of(x, y)] = char_to_insert;
        });
    }

    #[cfg(feature = "visualization")]
    painter.end_frame();

    if !found_keys.contains_key(&Key::new(b'@')) {
        return Err("No entrance ('@') found".to_string());
    }

    // Mapping to (other_key, needed_keys_to_reach, steps):
    let mut adjacency_list: HashMap<Key, Vec<Edge>> = HashMap::new();

    for (&this_key, &this_key_position) in found_keys.iter() {
        // Find path from this key to all other keys.

        // (position, bitset_of_needed_keys, steps):
        let mut to_visit = VecDeque::new();
        to_visit.push_back((this_key_position, 0_u32, 0_u32));

        let mut visited_positions = HashSet::new();
        visited_positions.insert(this_key_position);

        while let Some((position, needed_keys, steps)) = to_visit.pop_front() {
            'key_direction_loop: for direction in DIRECTIONS.iter() {
                let new_position = (position.0 + direction.0, position.1 + direction.1);
                if new_position.0 < 0 || new_position.1 < 0 {
                    continue 'key_direction_loop;
                }
                let mut new_needed_keys = needed_keys;
                let mut found_key = None;

                match map.get(index_of(new_position.0 as usize, new_position.1 as usize)) {
                    Some(&char_at_position @ b'A'..=b'Z') => {
                        let needed_key = Key::new(char_at_position.to_ascii_lowercase());
                        if found_keys.contains_key(&needed_key) {
                            // Only consider door as necessary if key is in quadrant.
                            // Needed by part 2, where we can wait until key is picked
                            // up in other quadrant.
                            new_needed_keys |= needed_key.bit_mask();
                        }
                    }
                    Some(&char_at_position @ b'a'..=b'z') => {
                        found_key = Some(Key::new(char_at_position));
                    }
                    Some(b'.') => {
                        // Free to enter.
                    }
                    _ => {
                        continue 'key_direction_loop;
                    }
                }

                let new_steps = steps + 1;
                if let Some(target_key) = found_key {
                    adjacency_list
                        .entry(this_key)
                        .or_insert_with(Vec::new)
                        .push(Edge {
                            steps: new_steps as usize,
                            needed_keys: new_needed_keys,
                            target_key,
                            #[cfg(feature = "visualization")]
                            x: new_position.0,
                            #[cfg(feature = "visualization")]
                            y: new_position.1,
                        });
                } else if visited_positions.insert(new_position) {
                    let new_state = (new_position, new_needed_keys, new_steps);
                    to_visit.push_back(new_state);
                }
            }
        }
    }

    shortest_path(
        &adjacency_list,
        all_keys_bitset,
        #[cfg(feature = "visualization")]
        &mut painter,
        #[cfg(feature = "visualization")]
        map_x_offset,
        #[cfg(feature = "visualization")]
        map_y_offset,
        #[cfg(feature = "visualization")]
        global_cols,
        #[cfg(feature = "visualization")]
        global_rows,
    )
    .ok_or_else(|| "Not possible to gather all keys".to_string())
}

fn shortest_path(
    adjacency_list: &HashMap<Key, Vec<Edge>>,
    all_keys: KeyBitset,
    #[cfg(feature = "visualization")] drawer: &mut PainterRef,
    #[cfg(feature = "visualization")] map_x_offset: usize,
    #[cfg(feature = "visualization")] map_y_offset: usize,
    #[cfg(feature = "visualization")] global_cols: usize,
    #[cfg(feature = "visualization")] global_rows: usize,
) -> Option<usize> {
    #[derive(Copy, Clone, Eq, PartialEq)]
    struct Vertex {
        at_key: Key,
        steps: usize,
        gathered_keys: KeyBitset,
        #[cfg(feature = "visualization")]
        x: i32,
        #[cfg(feature = "visualization")]
        y: i32,
    }

    impl Ord for Vertex {
        fn cmp(&self, other: &Self) -> Ordering {
            other
                .steps
                .cmp(&self.steps)
                .then_with(|| self.gathered_keys.cmp(&other.gathered_keys))
                .then_with(|| self.at_key.cmp(&other.at_key))
        }
    }

    impl PartialOrd for Vertex {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }

    // From (key, gathered_keys) to total steps required to reach there.
    let mut cost_for_keys: HashMap<(Key, KeyBitset), usize> = HashMap::new();
    let mut to_visit = BinaryHeap::new();

    #[cfg(feature = "visualization")]
    let mut visited_locations = HashSet::new();

    to_visit.push(Vertex {
        at_key: Key::new(b'@'),
        steps: 0,
        gathered_keys: 0,
        #[cfg(feature = "visualization")]
        x: 0,
        #[cfg(feature = "visualization")]
        y: 0,
    });

    while let Some(current) = to_visit.pop() {
        if current.gathered_keys == all_keys {
            return Some(current.steps);
        }

        #[cfg(feature = "visualization")]
        {
            if visited_locations.insert((current.x, current.y)) && current.at_key.value != b'@' {
                let canvas_x = (current.x + map_x_offset as i32) as f64 / global_cols as f64;
                let canvas_y = (current.y + map_y_offset as i32) as f64 / global_rows as f64;
                let draw_width = 0.95 / global_cols as f64;
                let draw_height = 0.95 / global_rows as f64;
                drawer.fill_style_rgb(80, 0, 80);
                drawer.fill_rect(canvas_x, canvas_y, draw_width, draw_height);
                drawer.meta_delay(50);
            }
        }

        for edge in adjacency_list.get(&current.at_key)? {
            let all_needed_keys_gathered =
                edge.needed_keys & current.gathered_keys == edge.needed_keys;
            if !all_needed_keys_gathered {
                continue;
            }

            let next = Vertex {
                steps: current.steps + edge.steps,
                at_key: edge.target_key,
                gathered_keys: current.gathered_keys | edge.target_key.bit_mask(),
                #[cfg(feature = "visualization")]
                x: edge.x,
                #[cfg(feature = "visualization")]
                y: edge.y,
            };

            let current_cost = cost_for_keys
                .entry((edge.target_key, next.gathered_keys))
                .or_insert(usize::max_value());

            if next.steps < *current_cost {
                to_visit.push(next);
                *current_cost = next.steps;
            }
        }
    }

    None
}

pub fn solve(input: &mut Input) -> Result<usize, String> {
    if input.is_part_one() {
        return steps_to_gather_all_keys(
            input.text,
            #[cfg(feature = "visualization")]
            &mut input.painter,
            #[cfg(feature = "visualization")]
            0,
            #[cfg(feature = "visualization")]
            0,
            #[cfg(feature = "visualization")]
            0,
            #[cfg(feature = "visualization")]
            0,
        );
    }

    let mut map_top_left = String::new();
    let mut map_top_right = String::new();
    let mut map_bottom_left = String::new();
    let mut map_bottom_right = String::new();

    let num_rows = input.text.lines().count();
    let num_columns = input
        .text
        .lines()
        .next()
        .ok_or("Invalid input - empty first line")?
        .len();
    let center_y = num_rows / 2;
    let center_x = num_columns / 2;

    input.text.lines().enumerate().for_each(|(y, line)| {
        line.chars().enumerate().for_each(|(x, c)| {
            let replaced_char = match (center_x as i32 - x as i32, center_y as i32 - y as i32) {
                (0, 0) | (1, 0) | (-1, 0) | (0, 1) | (0, -1) => '#',
                (1, 1) | (1, -1) | (-1, 1) | (-1, -1) => '@',
                _ => c,
            };

            if y <= center_y {
                if x <= center_x {
                    &mut map_top_left
                } else {
                    &mut map_top_right
                }
            } else if x <= center_x {
                &mut map_bottom_left
            } else {
                &mut map_bottom_right
            }
            .push(replaced_char);
        });
        if y <= center_y {
            map_top_left.push('\n');
            map_top_right.push('\n');
        } else {
            map_bottom_left.push('\n');
            map_bottom_right.push('\n');
        }
    });

    if !(map_top_left.starts_with('#')) {
        return Err("Invalid input (not surrounded by '#')".to_string());
    }

    let s1 = steps_to_gather_all_keys(
        &map_top_left,
        #[cfg(feature = "visualization")]
        &mut input.painter,
        #[cfg(feature = "visualization")]
        0,
        #[cfg(feature = "visualization")]
        0,
        #[cfg(feature = "visualization")]
        num_columns,
        #[cfg(feature = "visualization")]
        num_rows,
    )?;
    let s2 = steps_to_gather_all_keys(
        &map_top_right,
        #[cfg(feature = "visualization")]
        &mut input.painter,
        #[cfg(feature = "visualization")]
        {
            center_x + 1
        },
        #[cfg(feature = "visualization")]
        0,
        #[cfg(feature = "visualization")]
        num_columns,
        #[cfg(feature = "visualization")]
        num_rows,
    )?;
    let s3 = steps_to_gather_all_keys(
        &map_bottom_left,
        #[cfg(feature = "visualization")]
        &mut input.painter,
        #[cfg(feature = "visualization")]
        0,
        #[cfg(feature = "visualization")]
        {
            center_y + 1
        },
        #[cfg(feature = "visualization")]
        num_columns,
        #[cfg(feature = "visualization")]
        num_rows,
    )?;
    let s4 = steps_to_gather_all_keys(
        &map_bottom_right,
        #[cfg(feature = "visualization")]
        &mut input.painter,
        #[cfg(feature = "visualization")]
        {
            center_x + 1
        },
        #[cfg(feature = "visualization")]
        {
            center_y + 1
        },
        #[cfg(feature = "visualization")]
        num_columns,
        #[cfg(feature = "visualization")]
        num_rows,
    )?;
    Ok(s1 + s2 + s3 + s4)
}

#[test]
pub fn tests_part1() {
    assert_eq!(
        solve(&mut Input::part_one(
            "#########
#b.A.@.a#
#########"
        )),
        Ok(8)
    );

    assert_eq!(
        solve(&mut Input::part_one(
            "########################
#f.D.E.e.C.b.A.@.a.B.c.#
######################.#
#d.....................#
########################"
        )),
        Ok(86)
    );

    assert_eq!(
        solve(&mut Input::part_one(include_str!("day18_input.txt"))),
        Ok(4248)
    );
}

#[test]
fn tests_part2() {
    assert_eq!(
        solve(&mut Input::part_two(include_str!("day18_input.txt"))),
        Ok(1878)
    );
}