Skip to content

Instantly share code, notes, and snippets.

@alexgreenbank
Created December 12, 2021 12:39
Show Gist options
  • Save alexgreenbank/8a2dea0d56bdf989d3e4dc4c9f132533 to your computer and use it in GitHub Desktop.
Save alexgreenbank/8a2dea0d56bdf989d3e4dc4c9f132533 to your computer and use it in GitHub Desktop.
#!/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