@@ -138,8 +138,7 @@ pub fn part_two(input: &str) -> Option<u32> {
138138 }
139139
140140 // Simulate the path once so we know possible positions for obstructions
141- let mut visited = HashSet :: < ( usize , usize ) > :: new ( ) ;
142- visited. insert ( guard. pos ) ;
141+ let mut visited = Vec :: new ( ) ;
143142
144143 let mut visited_guard = guard. clone ( ) ;
145144
@@ -149,21 +148,29 @@ pub fn part_two(input: &str) -> Option<u32> {
149148 visited_guard. turn ( ) ;
150149 continue ;
151150 }
151+ visited. push ( ( visited_guard. pos . 0 , visited_guard. pos . 1 , visited_guard. direction . clone ( ) ) ) ;
152152 visited_guard. move_forward ( ) ;
153- if !visited. contains ( & ( nx, ny) ) {
154- visited. insert ( ( nx, ny) ) ;
155- continue ;
156- }
153+
157154 }
158155
159- visited . remove ( & guard . pos ) ;
156+ let mut placed_obstacles = HashSet :: < ( usize , usize ) > :: new ( ) ;
160157
161158 let mut sum = 0 ;
162159
163- visited. iter ( ) . for_each ( |( ox, oy) | {
160+ visited. iter ( ) . for_each ( |( ox, oy, direction ) | {
164161 let mut seen_position_directions = HashSet :: < ( usize , usize , Direction ) > :: new ( ) ;
165- let mut inner_guard = guard. clone ( ) ;
166- grid[ * oy] [ * ox] = true ;
162+ let mut inner_guard = Guard {
163+ pos : ( * ox, * oy) ,
164+ direction : direction. clone ( ) ,
165+ } ;
166+ let Some ( obstacle_pos) = inner_guard. next_pos ( grid[ 0 ] . len ( ) - 1 , grid. len ( ) - 1 ) else {
167+ return ;
168+ } ;
169+ if placed_obstacles. contains ( & obstacle_pos) {
170+ return ;
171+ }
172+ grid[ obstacle_pos. 1 ] [ obstacle_pos. 0 ] = true ;
173+ placed_obstacles. insert ( obstacle_pos) ;
167174 while let Some ( next_pos) =
168175 inner_guard. next_pos ( grid[ 0 ] . len ( ) - 1 , grid. len ( ) - 1 )
169176 {
@@ -190,12 +197,12 @@ pub fn part_two(input: &str) -> Option<u32> {
190197 inner_guard. pos . 1 ,
191198 inner_guard. direction . clone ( ) ,
192199 ) ) {
193- grid[ * oy ] [ * ox ] = false ;
200+ grid[ obstacle_pos . 1 ] [ obstacle_pos . 0 ] = false ;
194201 sum += 1 ;
195202 return ;
196203 }
197204 }
198- grid[ * oy ] [ * ox ] = false ;
205+ grid[ obstacle_pos . 1 ] [ obstacle_pos . 0 ] = false ;
199206 } ) ;
200207 Some ( sum)
201208}
0 commit comments