12th day both parts

This commit is contained in:
kplaczek
2021-12-12 21:23:29 +01:00
parent b39c1d5f1c
commit 67a7f89d87
4 changed files with 90 additions and 1 deletions

31
12/part2.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$input = array_map(fn($line) => explode('-', $line), $input);
$adjacencyList = [];
foreach ($input as $key => $item) {
if ($item[1] != 'start') $adjacencyList[$item[0]][] = $item[1];
if ($item[0] != 'start') $adjacencyList[$item[1]][] = $item[0];
}
$history = [];
echo track($adjacencyList, "start", $history, 0);
function track($adjacencyList, $cave, $history, $doubled)
{
$count = 0;
$history[] = $cave;
foreach ($adjacencyList[$cave] as $path) {
//small cave, not already visited
if ($path == "start") {
} elseif (strtolower($path) === $path && in_array($path, $history)) {
if ($doubled == 0) {
$count += track($adjacencyList, $path, $history, 1);
}
} elseif ($path == "end") {
$count += 1;
} else {
$count += track($adjacencyList, $path, $history, $doubled);
}
}
return $count;
}