@@ -35,8 +35,10 @@ pub fn parse(input: &str) -> Input<'_> {
35
35
pub fn part1 ( input : & Input < ' _ > ) -> i32 {
36
36
let ( grid, moves) = input;
37
37
38
+ // We don't need to move the robot symbol so mark as empty space once located.
38
39
let mut grid = grid. clone ( ) ;
39
40
let mut position = grid. find ( b'@' ) . unwrap ( ) ;
41
+ grid[ position] = b'.' ;
40
42
41
43
// Treat moves as a single string ignoring any newline characters.
42
44
for b in moves. bytes ( ) {
@@ -57,6 +59,7 @@ pub fn part2(input: &Input<'_>) -> i32 {
57
59
58
60
let mut grid = stretch ( grid) ;
59
61
let mut position = grid. find ( b'@' ) . unwrap ( ) ;
62
+ grid[ position] = b'.' ;
60
63
61
64
// Reuse to minimize allocations.
62
65
let mut todo = Vec :: new ( ) ;
@@ -78,7 +81,7 @@ pub fn part2(input: &Input<'_>) -> i32 {
78
81
79
82
fn narrow ( grid : & mut Grid < u8 > , start : & mut Point , direction : Point ) {
80
83
let mut position = * start + direction;
81
- let mut size = 2 ;
84
+ let mut size = 1 ;
82
85
83
86
// Search for the next wall or open space.
84
87
while grid[ position] != b'.' && grid[ position] != b'#' {
@@ -89,7 +92,7 @@ fn narrow(grid: &mut Grid<u8>, start: &mut Point, direction: Point) {
89
92
// Move items one space in direction.
90
93
if grid[ position] == b'.' {
91
94
let mut previous = b'.' ;
92
- let mut position = * start;
95
+ let mut position = * start + direction ;
93
96
94
97
for _ in 0 ..size {
95
98
swap ( & mut previous, & mut grid[ position] ) ;
@@ -110,12 +113,7 @@ fn wide(
110
113
id : usize ,
111
114
) {
112
115
// Short circuit if path in front of robot is empty.
113
- let position = * start;
114
- let next = position + direction;
115
-
116
- if grid[ next] == b'.' {
117
- grid[ position] = b'.' ;
118
- grid[ next] = b'@' ;
116
+ if grid[ * start + direction] == b'.' {
119
117
* start += direction;
120
118
return ;
121
119
}
@@ -151,8 +149,8 @@ fn wide(
151
149
}
152
150
}
153
151
154
- // Move boxes in reverse order.
155
- for & point in todo. iter ( ) . rev ( ) {
152
+ // Move boxes in reverse order (skipping the robot as an optimization) .
153
+ for & point in todo[ 1 .. ] . iter ( ) . rev ( ) {
156
154
grid[ point + direction] = grid[ point] ;
157
155
grid[ point] = b'.' ;
158
156
}
0 commit comments