#!/usr/bin/perl use v5.35.0; # Parse input map my ($width, @edge, @obstacle, $dir, $start); my $pos = 0; while (<>) { $width ||= length; for (split //) { $edge[$pos] = /\s/; $obstacle[$pos] = /#/; if ((my $i = index('^>v<', $_)) >= 0) { $dir = $i; $start = $pos; } $pos++; } } my @step = (-$width, 1, $width, -1); # Walk the guard's route my %visited = (); $pos = $start; for (;;) { $visited{$pos} = 1; # Mark route $pos += $step[$dir]; # Advance last unless 0 <= $pos < @edge; # Escape last if $edge[$pos]; if ($obstacle[$pos]) { # Obstacle? $pos -= $step[$dir]; # Retreat $dir++, $dir &= 3 # Turn right } } say scalar keys %visited;