problems / 208

Suki's Escape Route

medium bfs graphs shortest-paths 1000 ms · 256 MB

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:

  • S is Suki's starting position (exactly one).
  • G is the gate (exactly one).
  • T is the teleport pad entry (at most one).
  • E is the teleport pad exit (at most one; present only if T is 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, one G, and no other special markers.
  • If T is present, E is also present in the grid.
  • Steps are counted: each move to an adjacent open cell is 1 step; teleporting from T to E is 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.

Example 1

Input

3 4
S...
.#..
..#G

Output

5

Example 2

Input

4 5
S....
###T.
...E.
...G.

Output

6

Hints · reveal one at a time if you're stuck

Hint 1

Ignore the teleport for a moment. Every move costs one step, so what search finds the fewest steps to each cell?

Hint 2

Treat the teleport as one more move of cost 1 from T to E. Suki can always choose whether to take it, so does the search need to decide that in advance?

Hint 3

Run one search from S in which the cell T has an extra neighbour E. Record the first distance at which each cell is reached, and report the distance of G, or -1 if it is never reached.

report an issue Prefer your own editor? sooks prep 208 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.