use strict;
use warnings;
sub start_position {
my ($maze) = @_;
my @position;
foreach my $y (0..$#{$maze}){
foreach my $x (0..$#{$maze->[$y]}){
($maze->[$y][$x] eq 'S') and push(@position, [$x, $y]); }
}
}
sub step {
my ($maze, $x, $y) = @_;
my %done;
my @queue = ([$x, $y, []]);
while(@queue){
my ($x, $y, $step) = @{shift @queue}; foreach([0, -1, 'u'], [1, 0, 'r'], [0, 1, 'd'], [-1, 0, 'l']){
my ($nx, $ny, $dir) = ($x + $_->[0], $y + $_->[1], $_->[2]);
$done{"$nx,$ny"} and next;
my $p = $maze->[$ny][$nx];
($p eq 'G') and return (@{$step}, $dir); ($p eq '.') or next;
$done{"$nx,$ny"} = 1;
push(@queue, [$nx, $ny, [@{$step}, $dir]]); }
}
}
#######
#..S..#
#.....#
#..G..#
#######
#######
#.....#
#.G.#.#
#..#..#
#.#.S.#
#.....#
#######
########
#......#
#.G....#
#......#
#....S.#
#......#
########
EOF
say step(\@maze, @{$_}) foreach(start_position(\@maze));
dXNlIHN0cmljdDsKdXNlIHdhcm5pbmdzOwp1c2UgZmVhdHVyZSBxdyhzYXkpOwoKc3ViIHN0YXJ0X3Bvc2l0aW9uIHsKCW15ICgkbWF6ZSkgPSBAXzsKCglteSBAcG9zaXRpb247Cglmb3JlYWNoIG15ICR5ICgwLi4kI3skbWF6ZX0pewoJCWZvcmVhY2ggbXkgJHggKDAuLiQjeyRtYXplLT5bJHldfSl7CgkJCSgkbWF6ZS0+WyR5XVskeF0gZXEgJ1MnKSBhbmQgcHVzaChAcG9zaXRpb24sIFskeCwgJHldKTsKCQl9Cgl9CglyZXR1cm4gQHBvc2l0aW9uOwp9CgpzdWIgc3RlcCB7CglteSAoJG1hemUsICR4LCAkeSkgPSBAXzsKCglteSAlZG9uZTsKCW15IEBxdWV1ZSA9IChbJHgsICR5LCBbXV0pOwoKCXdoaWxlKEBxdWV1ZSl7CgkJbXkgKCR4LCAkeSwgJHN0ZXApID0gQHtzaGlmdCBAcXVldWV9OwoJ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