9th day both parts
This commit is contained in:
73
09/part2.php
Normal file
73
09/part2.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
$input = array_map('str_split', $input);
|
||||
|
||||
$sum = 0;
|
||||
$lowpoints = [];
|
||||
for ($i = 0; $i < count($input); $i++) {
|
||||
for ($j = 0; $j < count($input[0]); $j++) {
|
||||
$current = $input[$i][$j];
|
||||
|
||||
if (isset($input[$i - 1][$j]) && $input[$i - 1][$j] <= $current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($input[$i][$j - 1]) && $input[$i][$j - 1] <= $current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($input[$i][$j + 1]) && $input[$i][$j + 1] <= $current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($input[$i + 1][$j]) && $input[$i + 1][$j] <= $current) {
|
||||
continue;
|
||||
}
|
||||
$sum += $current + 1;
|
||||
$lowpoints[] = [$i + 1, $j + 1];
|
||||
}
|
||||
}
|
||||
$basinSizes = [];
|
||||
|
||||
$input = array_map(function ($line) {
|
||||
array_unshift($line, 9);
|
||||
array_push($line, 9);
|
||||
return $line;
|
||||
}, $input);
|
||||
|
||||
array_map(fn($line) => array_unshift($line, 9), $input);
|
||||
array_unshift($input, array_fill(0, count($input[0]), 9));
|
||||
$input[] = array_fill(0, count($input[0]), 9);
|
||||
|
||||
foreach ($lowpoints as $lowpoint) {
|
||||
$searched = [];
|
||||
$input[$lowpoint[0]][$lowpoint[1]] = '*';
|
||||
getBasinSize($input, $lowpoint[0], $lowpoint[1], $searched);
|
||||
$basinSizes[] = count($searched);
|
||||
}
|
||||
|
||||
function getBasinSize(&$input, $i, $j, &$searched)
|
||||
{
|
||||
if (!isset($searched[$i . ',' . $j])) {
|
||||
$searched[$i . ',' . $j] = 1;
|
||||
if ($input[$i][$j] != '*') {
|
||||
$input[$i][$j] = ' ';
|
||||
}
|
||||
if ($input[$i - 1][$j] != 9) {
|
||||
getBasinSize($input, $i - 1, $j, $searched);
|
||||
}
|
||||
if ($input[$i][$j - 1] != 9) {
|
||||
getBasinSize($input, $i, $j - 1, $searched);
|
||||
}
|
||||
if ($input[$i][$j + 1] != 9) {
|
||||
getBasinSize($input, $i, $j + 1, $searched);
|
||||
}
|
||||
if ($input[$i + 1][$j] != 9) {
|
||||
getBasinSize($input, $i + 1, $j, $searched);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rsort($basinSizes);
|
||||
echo array_product(array_slice($basinSizes, 0, 3)); //970200
|
||||
Reference in New Issue
Block a user