Files
advent_of_code_2021/15/part2.php
2021-12-18 14:51:23 +01:00

53 lines
1.5 KiB
PHP

<?php
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$input = array_map('str_split', $input);
$newInput = [];
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) {
foreach ($input as $row => $line) {
foreach ($line as $column => $number) {
// echo ($row + 1) * $i . '-' . ($column + 1) * $j . ' ';
$newNumber = ($number + $i + $j);
if ($newNumber > 9) {
$newNumber++;
}
$newInput[count($input) * $i + $row][count($input[0]) * $j + $column] = $newNumber%10;
}
}
}
}
$input = $newInput;
//foreach ($newInput as $line) {
// foreach ($line as $number) {
// echo $number . '';
// }
//// die();
// echo "\n";
//}
//die();
$visited = array_fill(0, count($input), array_fill(0, count($input[0]), PHP_INT_MAX));
$queue = [[0, 0]];
$visited[0][0] = 0;
while (count($queue) > 0) {
[$x, $y] = array_shift($queue);
//down
if (isset($input[$x + 1][$y]) &&
$visited[$x + 1][$y] > $visited[$x][$y] + $input[$x + 1][$y]
) {
$queue[] = [$x + 1, $y];
$visited[$x + 1][$y] = $visited[$x][$y] + $input[$x + 1][$y];
}
//right
if (isset($input[$x][$y + 1]) &&
$visited[$x][$y + 1] > $visited[$x][$y] + $input[$x][$y + 1]
) {
$queue[] = [$x, $y + 1];
$visited[$x][$y + 1] = $visited[$x][$y] + $input[$x][$y + 1];
}
}
echo $visited[count($visited) - 1][count($visited[0]) - 1]; //2858