-
-
Save alexgreenbank/8a2dea0d56bdf989d3e4dc4c9f132533 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl | |
| use strict; | |
| my %map=(); | |
| while( my $line = <STDIN> ) { | |
| chomp( $line ); | |
| if( $line =~ /^(.*)-(.*)$/ ) { | |
| my $f=$1; my $t=$2; | |
| push( @{$map{$f}}, $t ); | |
| push( @{$map{$t}}, $f ); | |
| } | |
| } | |
| my $routes=0; | |
| foreach my $poss ( @{$map{'start'}} ) { | |
| my %visited=(); go( "start", $poss, \%visited, 1 ); # Prevent any second visit | |
| } | |
| print "part1: $routes\n"; | |
| $routes=0; | |
| foreach my $poss ( @{$map{'start'}} ) { | |
| my %visited=(); go( "start", $poss, \%visited, 0 ); # Allow one second visit | |
| } | |
| print "part2: $routes\n"; | |
| exit; | |
| sub go { | |
| my ( $route, $where, $v, $vtwice ) = @_; | |
| $route .= ",$where"; # Add new location to route | |
| $v->{$where}++ if( $where eq lc($where) ); # If small cave mark it as done | |
| foreach my $poss ( @{$map{$where}} ) { | |
| next if( $poss eq "start" ); | |
| if( $poss eq "end" ) { | |
| $routes++; next; # Got a route to end, no need to go further | |
| } | |
| next if( exists( $v->{$poss} ) && $vtwice ); # Already been here and can't visit a second time | |
| my %visited=%$v; # Make a copy of the visited array to recurse with | |
| if( exists( $v->{$poss} ) ) { # If we've been here before, use up our second visit | |
| go( $route, $poss, \%visited, 1 ); | |
| } else { | |
| go( $route, $poss, \%visited, $vtwice ); # otherwise pass on existing value | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment