use strict;
use warnings;
use feature qw(say);

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]);
		}
	}
	return @position;
}

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]]);
		}
	}

	return;
}

my @maze = map{[split //]} split(/^/, <<'EOF');
#######
#..S..#
#.....#
#..G..#
#######

#######
#.....#
#.G.#.#
#..#..#
#.#.S.#
#.....#
#######

########
#......#
#.G....#
#......#
#....S.#
#......#
########
EOF

say step(\@maze, @{$_}) foreach(start_position(\@maze));
