foreach ($input->lines as $line) {
$sphere[] = explode(",", $line);
}
function get_sides($cube)
{
[$x, $y, $z] = $cube;
return [
[$x - 1, $y, $z],
[$x + 1, $y, $z],
[$x, $y + 1, $z],
[$x, $y - 1, $z],
[$x, $y, $z + 1],
[$x, $y, $z - 1]
];
}
function dfs($start, $sphere)
{
$todo = [$start];
$done = [];
while ($todo && count($done) < 15000) {
$current = array_shift($todo);
$done[] = $current;
foreach (get_sides($current) as $side) {
if ($current[0] < -1 || $current[1] < -1 || $current[2] < -1) continue;
if ($current[0] > 20 || $current[1] > 20|| $current[2] > 20) continue;
if (!in_array($side, $done) && !in_array($side, $todo) && !in_array($side, $sphere)) {
$todo[] = $side;
}
}
}
return $done;
}
function get_solution($sphere, $outside = [])
{
$sides = 0;
foreach ($sphere as $cube) {
$sides += 6;
foreach (get_sides($cube) as $side) {
if ($outside && !in_array($side, $outside)) {
$sides--;
} elseif (in_array($side, $sphere)) {
$sides--;
}
}
}
return $sides;
}
// ==================================================
// > SOLUTIONS
// ==================================================
$solution_1 = get_solution($sphere);
$solution_2 = get_solution($sphere, dfs([0, 0, 0], $sphere));