Skip to content

Commit e415ab5

Browse files
committed
part 2
1 parent 1352fba commit e415ab5

File tree

1 file changed

+57
-23
lines changed

1 file changed

+57
-23
lines changed

src/aoc2024/day6.rs

Lines changed: 57 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -34,41 +34,75 @@ impl ParseInput<Day6> for Aoc2024 {
3434

3535
impl Solution<Day6> for Aoc2024 {
3636
type Part1Output = usize;
37-
type Part2Output = u32;
37+
type Part2Output = usize;
3838

3939
fn part1((grid, sx, sy): &(Grid<bool>, usize, usize)) -> usize {
40-
const DIRECTIONS: [(isize, isize); 4] = [(0, -1), (1, 0), (0, 1), (-1, 0)];
41-
42-
let (mut x, mut y) = (*sx, *sy);
43-
let mut didx = 0;
44-
let mut positions = HashSet::new();
45-
46-
loop {
47-
positions.insert((x, y));
48-
let (dx, dy) = DIRECTIONS[didx];
49-
if let Some((nx, ny)) = offset_pair(grid, x, y, dx, dy) {
50-
if *grid.get(nx, ny) {
51-
didx = (didx + 1) % 4;
52-
} else {
53-
x = nx;
54-
y = ny;
40+
compute_path_size(grid, *sx, *sy).unwrap()
41+
}
42+
43+
fn part2((grid, sx, sy): &(Grid<bool>, usize, usize)) -> usize {
44+
let mut res = 0;
45+
for y in 0..grid.height {
46+
for x in 0..grid.width {
47+
if (x, y) == (*sx, *sy) {
48+
continue;
49+
}
50+
51+
if *grid.get(x, y) {
52+
continue;
53+
}
54+
55+
let mut ngrid = grid.clone();
56+
ngrid.set(x, y, true);
57+
58+
if compute_path_size(&ngrid, *sx, *sy).is_none() {
59+
res += 1;
5560
}
56-
} else {
57-
break;
5861
}
5962
}
6063

61-
positions.len()
64+
res
6265
}
66+
}
67+
68+
const DIRECTIONS: [(isize, isize); 4] = [(0, -1), (1, 0), (0, 1), (-1, 0)];
6369

64-
fn part2(_input: &(Grid<bool>, usize, usize)) -> u32 {
65-
todo!()
70+
fn compute_path_size(grid: &Grid<bool>, sx: usize, sy: usize) -> Option<usize> {
71+
let (mut x, mut y) = (sx, sy);
72+
let mut didx = 0;
73+
let mut positions = HashSet::new();
74+
let mut pos_and_dir = HashSet::new();
75+
76+
loop {
77+
positions.insert((x, y));
78+
if !pos_and_dir.insert((x, y, didx)) {
79+
return None;
80+
}
81+
let (dx, dy) = DIRECTIONS[didx];
82+
if let Some((nx, ny)) = offset_pair(grid, x, y, dx, dy) {
83+
if *grid.get(nx, ny) {
84+
didx = (didx + 1) % 4;
85+
} else {
86+
x = nx;
87+
y = ny;
88+
}
89+
} else {
90+
break;
91+
}
6692
}
93+
94+
Some(positions.len())
6795
}
6896

69-
fn offset_pair(grid: &Grid<bool>, x: usize, y: usize, dx: isize, dy: isize) -> Option<(usize, usize)> {
97+
fn offset_pair(
98+
grid: &Grid<bool>,
99+
x: usize,
100+
y: usize,
101+
dx: isize,
102+
dy: isize,
103+
) -> Option<(usize, usize)> {
70104
let nx = offset(x, dx, grid.width);
71-
let ny = offset(y, dy,grid.height);
105+
let ny = offset(y, dy, grid.height);
72106

73107
match (nx, ny) {
74108
(Some(nx), Some(ny)) => Some((nx, ny)),

0 commit comments

Comments
 (0)