Guest User

Untitled

a guest
Dec 12th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.91 KB | None | 0 0
  1. <?php
  2.  
  3. ini_set('memory_limit', -1);
  4.  
  5. function readInput(): array
  6. {
  7.     $lines = [];
  8.  
  9.     $f = fopen( 'php://stdin', 'r' );
  10.  
  11.     while( $line = fgets( $f ) ) {
  12.         $withOutNewLine = str_replace(PHP_EOL,'',$line);
  13.         if ($withOutNewLine != '') {
  14.             $lines[] = $withOutNewLine;
  15.         }
  16.     }
  17.  
  18.     fclose($f);
  19.  
  20.     return $lines;
  21. }
  22.  
  23. $input = readInput();
  24.  
  25. $graph = [];
  26.  
  27. foreach ($input as $line) {
  28.     $connection = explode('-',$line);
  29.     if (!array_key_exists($connection[0], $graph)) {
  30.         $graph[$connection[0]] = [];
  31.     }
  32.  
  33.     if (!array_key_exists($connection[1], $graph)) {
  34.         $graph[$connection[1]] = [];
  35.     }
  36.  
  37.     if ($connection[0] == 'start') {
  38.         $graph[$connection[0]][] = $connection[1];
  39.         continue;
  40.     }
  41.  
  42.     if ($connection[1] == 'end') {
  43.         $graph[$connection[0]][] = $connection[1];
  44.         continue;
  45.     }
  46.  
  47.     $graph[$connection[0]][] = $connection[1];
  48.  
  49.     $graph[$connection[1]][] = $connection[0];
  50. }
  51.  
  52. $total = [
  53.     'count' => 0
  54. ];
  55.  
  56. countPaths('start', $graph, $total, 'fuck', []);
  57.  
  58. echo $total['count'] . PHP_EOL;
  59.  
  60. function countPaths($currentNode, $graph, &$counter, $previous, $smallVisited)
  61. {
  62.     if ($currentNode == 'end') {
  63.         $counter['count']++;
  64.  
  65.         return;
  66.     }
  67.  
  68.     if (ctype_lower($currentNode) && $currentNode != 'start') {
  69.         $smallVisited[$currentNode] = ($smallVisited[$currentNode] ?? 0) + 1;
  70.     }
  71.  
  72.     foreach ($graph[$currentNode] as $neighbour) {
  73.         if (ctype_upper($currentNode) && ctype_upper($neighbour) && $neighbour == $previous) {
  74.             continue;
  75.         }
  76.  
  77.         if ($neighbour == 'start') {
  78.             continue;
  79.         }
  80.  
  81.         if (($smallVisited[$neighbour] ?? 0) >= 1 && max(array_values($smallVisited)) > 1) {
  82.             continue;
  83.         }
  84.        
  85.         countPaths($neighbour, $graph, $counter, $currentNode, $smallVisited);
  86.     }
  87. }
Add Comment
Please, Sign In to add comment