4 use experimental 'multidimensional';
8 my @map = map { chomp; [ split // ] } <>;
9 my $xmax = $#{ $map[0] };
12 my @dx = (1, 0, -1, 0);
13 my @dy = (0, 1, 0, -1);
16 push_heap @q, [ $xmax + $ymax, 0, 0, 0, 4, [0, 0] ];
18 $min_cost{0,0,0} = 0; # $x, $y, $dir
20 my $node = pop_heap @q;
21 my ($w, $x, $y, $cost, $prevdir, @path) = @$node;
23 if ($x == $xmax && $y == $ymax) {
24 say "$cost : ", join(', ', map { join(',', @$_) } @path);
29 for my $dir (0 .. 3) {
30 next if $dir == ($prevdir ^ 2) || $dir == $prevdir;
37 next DIR if $nx > $xmax || $ny > $ymax || $nx < 0 || $ny < 0;
38 $ncost += $map[$ny][$nx];
40 next if defined $min_cost{$nx,$ny,$dir}
41 && $min_cost{$nx,$ny,$dir} <= $ncost;
42 $min_cost{$nx,$ny,$dir} = $ncost;
43 my $nw = ($xmax-$nx) + ($ymax-$ny) + $ncost;
44 push_heap @q, [ $nw, $nx, $ny, $ncost, $dir, @path, [$nx, $ny] ];