Skip to main content
Tuesday (24.11.2026) at 20:00: ALGOR Contest: Round #4 (Special Challenge) starts!

~/algor $ cat problems/graf-labirint

Maze

Hard 2000 ms 128 MB 67%
Share

An n × m maze is given: «.» is a free cell, «#» is a wall, «S» is the start, «E» is the exit. In one step you may move to an adjacent (up, down, left or right) free cell; you cannot pass through walls or leave the maze. What is the smallest number of steps from S to E? If E cannot be reached, print −1.

Maze: the shortest path from S to E is 6 steps

Input

The first line contains n and m. Each of the next n lines contains m characters. S and E each appear exactly once.

Output

One integer — the smallest number of steps or −1.

Note

1 ≤ n, m ≤ 1000; n · m ≥ 2

Examples

Input #1
3 4
S..#
.#..
...E
Output #1
5
Input #2
3 3
S#E
.#.
.#.
Output #2
-1

Sign in to submit a solution

Signing up is free and takes a minute.