cswork / OAOpen practice workspace

SnowflakeOA #14

Grid Traversal

Estimated HardJudge-ready

Topics (AI-labelled)Shortest PathsGrid Search

The grid contains empty cells *, walls #, a start S, and an end E. Each move jumps a positive integer distance up, down, left, or right; a jump may pass over walls but cannot land on a wall. If the previous jump had length >1, the next jump must go in the same direction; a jump of length 1 lifts the restriction. E counts as reached only when the last move has length 1 and lands on E. If E cannot be reached, output −1.

Input

The first line contains n m, followed by n lines of the grid; 2≤n,m≤100, and there is exactly one S and exactly one E.

Output

Output the single integer required by the problem.

Example 1

Input:

2 2
SE
**

Output:

1

Example 2

Input:

2 3
S#E
***

Output:

4

Example 3

Input:

2 2
S#
#E

Output:

-1

Example notes

The answers to the three public examples are, in order: 1; 4; -1. All examples have been verified by independent small-scale enumeration or state search.

Editorial

Loading solution…