fork download
  1. use strict;
  2. use warnings;
  3. use feature qw(say);
  4.  
  5. sub start_position {
  6. my ($maze) = @_;
  7.  
  8. my @position;
  9. foreach my $y (0..$#{$maze}){
  10. foreach my $x (0..$#{$maze->[$y]}){
  11. ($maze->[$y][$x] eq 'S') and push(@position, [$x, $y]);
  12. }
  13. }
  14. return @position;
  15. }
  16.  
  17. sub step {
  18. my ($maze, $x, $y) = @_;
  19.  
  20. my %done;
  21. my @queue = ([$x, $y, []]);
  22.  
  23. while(@queue){
  24. my ($x, $y, $step) = @{shift @queue};
  25. foreach([0, -1, 'u'], [1, 0, 'r'], [0, 1, 'd'], [-1, 0, 'l']){
  26. my ($nx, $ny, $dir) = ($x + $_->[0], $y + $_->[1], $_->[2]);
  27. $done{"$nx,$ny"} and next;
  28.  
  29. my $p = $maze->[$ny][$nx];
  30. ($p eq 'G') and return (@{$step}, $dir);
  31. ($p eq '.') or next;
  32.  
  33. $done{"$nx,$ny"} = 1;
  34. push(@queue, [$nx, $ny, [@{$step}, $dir]]);
  35. }
  36. }
  37.  
  38. }
  39.  
  40. my @maze = map{[split //]} split(/^/, <<'EOF');
  41. #######
  42. #..S..#
  43. #.....#
  44. #..G..#
  45. #######
  46.  
  47. #######
  48. #.....#
  49. #.G.#.#
  50. #..#..#
  51. #.#.S.#
  52. #.....#
  53. #######
  54.  
  55. ########
  56. #......#
  57. #.G....#
  58. #......#
  59. #....S.#
  60. #......#
  61. ########
  62. EOF
  63.  
  64. say step(\@maze, @{$_}) foreach(start_position(\@maze));
  65.  
Success #stdin #stdout 0s 4728KB
stdin
Standard input is empty
stdout
dd
uruulldl
uulll