Skip to content

Commit 5ea7fc8

Browse files
committed
complete day 12
1 parent 1e29b48 commit 5ea7fc8

File tree

1 file changed

+55
-2
lines changed

1 file changed

+55
-2
lines changed

src/Days/Day12.php

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,62 @@ public function solvePart1(mixed $input): int|string|null
8383
public function solvePart2(mixed $input): int|string|null
8484
{
8585
$grid = $this->parseInput($input)->toArray();
86-
dd($grid);
8786

88-
return null;
87+
$rows = count($grid);
88+
$cols = count($grid[0]);
89+
90+
// Find start and end positions
91+
$startingPoints = [];
92+
$end = null;
93+
foreach ($grid as $y => $row) {
94+
foreach ($row as $x => $cell) {
95+
match ($cell) {
96+
'S' => [$startingPoints[], $grid[$y][$x]] = [[$y, $x], 'a'],
97+
'E' => [$end, $grid[$y][$x]] = [[$y, $x], 'z'],
98+
'a' => $startingPoints[] = [$y, $x],
99+
default => null,
100+
};
101+
}
102+
}
103+
104+
return $this->bfs($grid, $startingPoints, $end, $rows, $cols);
105+
}
106+
107+
protected function bfs(array $grid, array $startingPoints, array $end, int $rows, int $cols): int|string|null
108+
{
109+
$queue = new SplQueue();
110+
foreach ($startingPoints as $point) {
111+
$queue->enqueue([$point, 0]); // [position, steps]
112+
}
113+
114+
$visited = array_fill(0, $rows, array_fill(0, $cols, false));
115+
foreach ($startingPoints as $point) {
116+
$visited[$point[0]][$point[1]] = true;
117+
}
118+
119+
while (!$queue->isEmpty()) {
120+
[$current, $steps] = $queue->dequeue();
121+
[$x, $y] = $current;
122+
123+
if ($current === $end) {
124+
return $steps; // found the shortest path
125+
}
126+
127+
foreach ($this->directions as [$dx, $dy]) {
128+
$newX = $x + $dx;
129+
$newY = $y + $dy;
130+
131+
if ($newX >= 0 && $newX < $rows && $newY >= 0 && $newY < $cols
132+
&& !$visited[$newX][$newY]
133+
&& ord($grid[$newX][$newY]) <= ord($grid[$x][$y]) + 1
134+
) {
135+
$queue->enqueue([[$newX, $newY], $steps + 1]);
136+
$visited[$newX][$newY] = true;
137+
}
138+
}
139+
}
140+
141+
return null; // no path found
89142
}
90143

91144
/**

0 commit comments

Comments
 (0)