summaryrefslogtreecommitdiff
path: root/2022/src/bin/day_12.rs
blob: 9190113647be358cf79b4e572c72f2e337b32a8d (plain)
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
use nom::{
    character::complete::{line_ending, satisfy},
    combinator::map,
    multi::{many1, separated_list1},
    IResult,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_12.txt")?;
    let map = HeightMap::parser(&input).unwrap().1;

    let distance_map = MapExploration::explore(&map);

    dbg!(distance_map.distance_to.get(&map.start));

    let min_distance_start = map
        .heights
        .iter()
        .enumerate()
        .flat_map(|(y, row)| {
            row.iter()
                .enumerate()
                .filter(|(_x, height)| **height == 0)
                .map(move |(x, _)| Point { x, y })
        })
        .filter_map(|p| distance_map.distance_to.get(&p))
        .min();
    dbg!(min_distance_start);

    Ok(())
}

#[derive(Debug, Clone)]
struct HeightMap {
    heights: Vec<Vec<u8>>,
    start: Point,
    end: Point,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Point {
    x: usize,
    y: usize,
}

impl HeightMap {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            separated_list1(line_ending, many1(satisfy(|c| c.is_ascii_alphabetic()))),
            |height_chars| {
                let mut start = Point::default();
                let mut end = Point::default();
                let mut heights = Vec::new();
                for y in 0..height_chars.len() {
                    let mut new_row = Vec::new();
                    for x in 0..height_chars[y].len() {
                        let height = match height_chars[y][x] {
                            'S' => {
                                start = Point { x, y };
                                0
                            }
                            'E' => {
                                end = Point { x, y };
                                25
                            }
                            a if a.is_ascii_lowercase() => height_chars[y][x] as u8 - b'a',
                            a => panic!("Unexpected character {}", a),
                        };
                        new_row.push(height);
                    }
                    heights.push(new_row);
                }

                HeightMap {
                    heights,
                    start,
                    end,
                }
            },
        )(input)
    }

    fn adjacent_to(&self, p: &Point) -> Vec<Point> {
        let current_height = self
            .heights
            .get(p.y)
            .and_then(|row| row.get(p.x))
            .cloned()
            .unwrap_or(0);

        p.adjacent()
            .into_iter()
            .filter(|other_p| {
                let other_height = self
                    .heights
                    .get(other_p.y)
                    .and_then(|row| row.get(other_p.x));

                match other_height {
                    None => false,
                    Some(&other_height) => other_height + 1 >= current_height,
                }
            })
            .collect()
    }
}

impl Point {
    fn adjacent(&self) -> Vec<Point> {
        let mut result = Vec::new();
        if self.x > 0 {
            result.push(Point {
                x: self.x - 1,
                y: self.y,
            });
        }
        if self.x < usize::MAX {
            result.push(Point {
                x: self.x + 1,
                y: self.y,
            });
        }
        if self.y > 0 {
            result.push(Point {
                x: self.x,
                y: self.y - 1,
            });
        }
        if self.y < usize::MAX {
            result.push(Point {
                x: self.x,
                y: self.y + 1,
            });
        }
        result
    }
}

struct MapExploration {
    distance_to: BTreeMap<Point, u32>,
}

impl MapExploration {
    fn explore(map: &HeightMap) -> MapExploration {
        let mut frontier = BTreeSet::new();
        let mut distance_to = BTreeMap::new();
        let mut distance = 0;

        distance_to.insert(map.end.clone(), distance);
        frontier.insert(map.end.clone());

        while !frontier.is_empty() {
            let mut next_frontier = BTreeSet::new();
            distance += 1;

            for frontier_point in frontier {
                for adjacent_point in map.adjacent_to(&frontier_point) {
                    if !distance_to.contains_key(&adjacent_point) {
                        distance_to.insert(adjacent_point.clone(), distance);
                        next_frontier.insert(adjacent_point);
                    }
                }
            }

            frontier = next_frontier;
        }

        MapExploration { distance_to }
    }
}