#!/usr/bin/perl -w

use v5.36;
use strict;
use experimental 'multidimensional';

my @m = map { chomp; [ split // ] } <>;

my $xmax = $#{ $m[0] };
my $ymax = $#m;

my ($sx, $sy);
for my $y (0 .. $ymax) {
	for my $x (0 .. $xmax) {
		if ($m[$y][$x] eq 'E') {
			$m[$y][$x] = 'z';
			$sx = $x; $sy = $y;
		}
		if ($m[$y][$x] eq 'S') {
			$m[$y][$x] = 'a';
		}
	}
}

my %seen;
my @q = [ $sx, $sy ];

my $minp;

while (@q) {
	my $pt = shift @q;
	my ($x, $y, @path) = @$pt;

	say "walking ", join(' ', @$pt);

	my $h = $m[$y][$x];

	next if $seen{"$x,$y"}++;

	if ($h eq 'a') {
		say "FOUND";
		say scalar @path, ': ', @path;
		exit 0;
	}

	for my $pt1 ([-1, 0], [1, 0], [0, -1], [0, 1]) {
		my ($dx, $dy) = @$pt1;
		my ($nx, $ny) = ($x+$dx, $y+$dy);
		next if $nx > $xmax || $nx < 0 || $ny > $ymax || $ny < 0;
		my $h1 = $m[$ny][$nx];
		say "trying $nx $ny $h $h1";
		next if ord($h1)-ord($h) < -1;
		push @q, [ $nx, $ny, @path, " $nx,$ny" ];
	}
}

say "Min: $minp";
