|
| 1 | +use std::convert::identity; |
| 2 | + |
1 | 3 | use super::*; |
| 4 | +use pathfinding::prelude::bfs; |
| 5 | + |
| 6 | +#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 7 | +struct Pos(usize, usize); |
| 8 | + |
| 9 | +impl Pos { |
| 10 | + fn successors(&self, map: &Vec<Vec<u8>>) -> Vec<Pos> { |
| 11 | + let &Pos(x, y) = self; |
| 12 | + let mut result = Vec::new(); |
| 13 | + let max_target = map[x][y] + 1; |
| 14 | + if x > 0 && map[x - 1][y] <= max_target { |
| 15 | + result.push(Pos(x - 1, y)); |
| 16 | + } |
| 17 | + if x < map.len() - 1 && map[x + 1][y] <= max_target { |
| 18 | + result.push(Pos(x + 1, y)); |
| 19 | + } |
| 20 | + if y > 0 && map[x][y - 1] <= max_target { |
| 21 | + result.push(Pos(x, y - 1)); |
| 22 | + } |
| 23 | + if y < map[x].len() - 1 && map[x][y + 1] <= max_target { |
| 24 | + result.push(Pos(x, y + 1)); |
| 25 | + } |
| 26 | + result |
| 27 | + } |
| 28 | +} |
2 | 29 |
|
3 | 30 | pub fn solve(filename: String) { |
4 | 31 | if let Ok(lines) = read_lines(&filename) { |
5 | 32 | // Consumes the iterator, returns an (Optional) String |
| 33 | + let mut map: Vec<Vec<u8>> = Vec::new(); |
| 34 | + let mut x = 0; |
| 35 | + let mut target = Pos(0, 0); |
| 36 | + let mut start = Pos(0, 0); |
| 37 | + let mut starts: Vec<Pos> = Vec::new(); |
6 | 38 | for line in lines { |
7 | 39 | if let Ok(ip) = line { |
8 | | - println!("{}", ip) |
| 40 | + map.push(ip.chars().map(|c| c as u8).collect()); |
| 41 | + map[map.len() - 1].iter().enumerate().for_each(|(y, c)| { |
| 42 | + if *c == ('E' as u8) { |
| 43 | + target = Pos(x, y); |
| 44 | + } |
| 45 | + if *c == ('S' as u8) { |
| 46 | + start = Pos(x, y); |
| 47 | + starts.push(Pos(x, y)); |
| 48 | + } |
| 49 | + if *c == ('a' as u8) { |
| 50 | + starts.push(Pos(x, y)); |
| 51 | + } |
| 52 | + }); |
9 | 53 | } |
| 54 | + x += 1; |
10 | 55 | } |
| 56 | + let Pos(x, y) = target; |
| 57 | + map[x][y] = 'z' as u8; |
| 58 | + let Pos(x, y) = start; |
| 59 | + map[x][y] = 'a' as u8; |
| 60 | + let result = bfs(&start, |p| p.successors(&map), |p| *p == target); |
| 61 | + println!("{:?}", result.expect("").len() - 1); |
| 62 | + let lens = starts |
| 63 | + .iter() |
| 64 | + .map(|s| bfs(s, |p| p.successors(&map), |p| *p == target)) |
| 65 | + .filter_map(identity) |
| 66 | + .map(|r| r.len() - 1).min(); |
| 67 | + println!("{:?}", lens) |
11 | 68 | } |
12 | 69 | } |
13 | | - |
|
0 commit comments