Answer ⏱ 2734ms
Part 1 :
7210
Part 2 :
7673
function solve($start, $grid) {
$queue = [$start];
while ($queue) {
[$x, $y, $dir] = array_shift($queue);
if (isset($seen["$x;$y;$dir"])) continue;
$seen["$x;$y;$dir"] = true;
$enerygized["$x;$y"] = true;
$dirs = match ($grid[$y][$x]) {
"-" => match($dir) {"v", "^" => ["<", ">"], default => [$dir]},
"|" => match($dir) {">", "<" => ["^", "v"], default => [$dir]},
"/" => [[">" => "^", "<" => "v", "^" => ">", "v" => "<"][$dir]],
"\\" => [[">" => "v", "<" => "^", "^" => "<", "v" => ">"][$dir]],
default => [$dir]
};
foreach ($dirs as $dir) {
[$nx, $ny] = match ($dir) {
">" => [$x + 1, $y],
"<" => [$x - 1, $y],
"^" => [$x, $y - 1],
default => [$x, $y + 1],
};
if (!isset($grid[$ny][$nx])) continue;
$queue[] = [$nx, $ny, $dir];
}
}
return count($enerygized);
}
// ==================================================
// > PART 1
// ==================================================
$grid = array_map("str_split", explode("\n", $input));
$solution_1 = solve([0, 0, ">"], $grid);
// ==================================================
// > PART 2
// ==================================================
foreach (range(0, count($grid) - 1) as $y) {
$s[] = solve([0, $y, ">"], $grid);
$s[] = solve([count($grid) - 1, $y, "<"], $grid);
}
foreach (range(0, count($grid[0]) - 1) as $x) {
$s[] = solve([$x, 0, "v"], $grid);
$s[] = solve([$x, count($grid[0]) - 1, "^"], $grid);
}
$solution_2 = max($s);