Suki's Escape Route
Suki the dog has been napping in her yard and now realizes she's forgotten the afternoon walk! The gate is locked, but she knows the way out—if she can navigate the hedges and use the secret teleport pad. The yard is a grid of cells, some blocked by hedges (#), some open (.'). Suki starts at position S, and the gate is at position G. There's also a special pink teleport pad at position Tthat instantly moves her to positionE` (the pad's exit). Using the teleport is free and takes one step; not using it is Suki's choice when she reaches the pad.
Find the shortest path from Suki's starting position to the gate, where she can move up, down, left, or right to any adjacent open cell. The teleport pad works one-way: stepping onto T instantly moves her to E in a single step. Find the minimum number of steps to reach the gate, or report if escape is impossible.
Input
The first line contains two integers r and c (1 ≤ r, c ≤ 500) — the dimensions of the yard.
The next r lines each contain a string of c characters representing the yard:
Sis Suki's starting position (exactly one).Gis the gate (exactly one).Tis the teleport pad entry (at most one).Eis the teleport pad exit (at most one; present only ifTis present).#is a hedge (blocked cell)..is an open cell.
All positions are guaranteed to be within bounds and distinct.
Output
Print the minimum number of steps needed for Suki to reach the gate, or -1 if escape is impossible.
Constraints
- 1 ≤ r, c ≤ 500
- The grid contains at least one
S, oneG, and no other special markers. - If
Tis present,Eis also present in the grid. - Steps are counted: each move to an adjacent open cell is 1 step; teleporting from
TtoEis 1 step.
Notes
In the first example, Suki starts at S, can move through open cells, and reaches the gate at G without needing the teleport.
In the second example, a wall blocks the direct path, but the teleport allows Suki to bypass it and reach the gate.