Advertisement
musifter

AoC 2023 day 23, part 1 (Perl)

Dec 23rd, 2023 (edited)
761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.27 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7.  
  8. $| = 1;
  9.  
  10. use Math::Vector::Real;
  11.  
  12. my ($Y,$X) = Math::Vector::Real->canonical_base(2);
  13. my %Dirs = ( '.' => [$Y, $X, -$Y, -$X],
  14.              '>' => [ $X], '<' => [-$X], '^' => [-$Y], 'v' => [ $Y] );
  15.  
  16. # Read in grid:
  17. my @Grid = map { chomp; [split(//)] } <>;
  18.  
  19. sub grid_at ($) { my $p = shift; return ($Grid[$p->[0]][$p->[1]]) }
  20. sub print_grid  { say "\t", join( '', @$_ ) foreach (@Grid); }
  21.  
  22. my $start = V(0,1);
  23. my $end   = V($#Grid, $Grid[0]->$#* - 1);
  24.  
  25. say "Start: $start";
  26. say "End:   $end";
  27.  
  28. $Grid[$start->[0]][$start->[1]] = 'S';
  29. my @queue = ([$start + $Y, $start => 1]);
  30. my $part1 = 0;
  31.  
  32. my $time = 0;
  33. STEP:
  34. while (my $state = shift @queue) {
  35.     my ($pos, %path) = @$state;
  36.  
  37.     say "At $pos (", scalar @queue, ")"   if (++$time % 10000 == 0);
  38.  
  39.     if ($pos == $end) {
  40.         if (scalar %path > $part1) {
  41.             $part1 = scalar %path;
  42.             say "Found $part1";
  43.         }
  44.         next STEP;
  45.     }
  46.  
  47.     DIR:
  48.     foreach my $d ($Dirs{&grid_at($pos)}->@*) {
  49.         my $npos = $pos + $d;
  50.         next DIR if (&grid_at($npos) eq '#');
  51.         next DIR if (exists $path{$npos});
  52.  
  53.         push( @queue, [$npos, %path, $npos => 1] );
  54.     }
  55. }
  56.  
  57. say "Part 1: $part1";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement