Advertisement
musifter

AoC 2021, day 12 pt 2 (Perl)

Dec 11th, 2021
2,524
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.90 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. my %Graph;
  7.  
  8. # read in graph
  9. while (<>) {
  10.     my ($a, $b) = m#(start|end|..)-(start|end|..)#;
  11.  
  12.     push( @{$Graph{$a}}, $b );
  13.     push( @{$Graph{$b}}, $a );
  14. }
  15.  
  16. sub recurse_path {
  17.     my ($loc, $double, %visit) = @_;
  18.     my $ret = 0;
  19.  
  20.     # reached end, return 1 way
  21.     return (1) if ($loc eq 'end');
  22.  
  23.     # handle small cave... set double if second time here
  24.     if ($loc eq lc($loc)) {
  25.         $visit{$loc}++;
  26.         $double = 1 if ($visit{$loc} == 2);
  27.     }
  28.  
  29.     # recurse to valid neighbours
  30.     foreach my $neigh (@{$Graph{$loc}}) {
  31.         next if ($neigh eq 'start');                    # only once ever
  32.         next if (exists $visit{$neigh} && $double);     # this would be a second double
  33.  
  34.         $ret += &recurse_path( $neigh, $double, %visit );
  35.     }
  36.  
  37.     return ($ret);
  38. }
  39.  
  40. print "Part 2: ", &recurse_path( 'start', 0 ), "\n";
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement