BEGIN { FS = ""; y = 1; } function elev(a) { return index("abcdefghijklmnopqrstuvwxyz", a); } { for (x = 1; x <= NF; ++x) { if ($x == "S") { S = x "," y; m[x,y] = elev("a"); } else if ($x == "E") { E = x "," y; m[x,y] = elev("z"); } else { m[x,y] = elev($x); } } y++; w = NF; h = NR; } END { l = 1; Q[l] = S; N[l] = 0; for (i = 1; Q[i]; ++i) { if (Q[i] == E) break; split(Q[i], a, ","); x = a[1]; y = a[2]; n = N[i]; if (x > 1 && !V[x-1,y] && m[x-1,y] <= m[x,y]+1) { V[x-1,y] = 1; Q[++l] = x-1 "," y; N[l] = n+1; } if (x < w && !V[x+1,y] && m[x+1,y] <= m[x,y]+1) { V[x+1,y] = 1; Q[++l] = x+1 "," y; N[l] = n+1; } if (y > 1 && !V[x,y-1] && m[x,y-1] <= m[x,y]+1) { V[x,y-1] = 1; Q[++l] = x "," y-1; N[l] = n+1; } if (y < h && !V[x,y+1] && m[x,y+1] <= m[x,y]+1) { V[x,y+1] = 1; Q[++l] = x "," y+1; N[l] = n+1; } delete Q[i]; delete N[i]; } print N[i]; }