@@ -34,41 +34,75 @@ impl ParseInput<Day6> for Aoc2024 {
34
34
35
35
impl Solution < Day6 > for Aoc2024 {
36
36
type Part1Output = usize ;
37
- type Part2Output = u32 ;
37
+ type Part2Output = usize ;
38
38
39
39
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 ;
55
60
}
56
- } else {
57
- break ;
58
61
}
59
62
}
60
63
61
- positions . len ( )
64
+ res
62
65
}
66
+ }
67
+
68
+ const DIRECTIONS : [ ( isize , isize ) ; 4 ] = [ ( 0 , -1 ) , ( 1 , 0 ) , ( 0 , 1 ) , ( -1 , 0 ) ] ;
63
69
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
+ }
66
92
}
93
+
94
+ Some ( positions. len ( ) )
67
95
}
68
96
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 ) > {
70
104
let nx = offset ( x, dx, grid. width ) ;
71
- let ny = offset ( y, dy, grid. height ) ;
105
+ let ny = offset ( y, dy, grid. height ) ;
72
106
73
107
match ( nx, ny) {
74
108
( Some ( nx) , Some ( ny) ) => Some ( ( nx, ny) ) ,
0 commit comments