#C1214. Minimum Moves to Reach Destination

    ID: 41534 Type: Default 1000ms 256MiB

Minimum Moves to Reach Destination

Minimum Moves to Reach Destination

You are given an n x n grid representing a city. Each cell in the grid can either be:

  • 'S' - the starting point.
  • 'E' - the destination.
  • '.' - an open space.
  • '#' - an obstacle that cannot be crossed.

Your task is to compute the minimum number of moves required to reach 'E' from 'S'. Moves are allowed in four directions: up, down, left, and right. If there is no possible path between 'S' and 'E', output -1.

The problem can be mathematically formulated as finding the shortest path on a grid graph. Let \(d(i,j)\) denote the minimum number of moves required to reach cell \((i,j)\) from the starting cell. Then, the relation is given by:

\[ d(i,j) = 1 + \min_{(i',j') \in \{(i-1,j), (i+1,j), (i,j-1), (i,j+1)\}} d(i',j') \]

with appropriate boundary conditions and obstacle checks.

inputFormat

The input is read from stdin and has the following format:

  1. The first line contains an integer n representing the size of the grid.
  2. The following n lines each contain a string of length n which represents a row of the grid. The grid is composed of the characters 'S', 'E', '.', and '#' as described.

outputFormat

Output a single integer to stdout which is the minimum number of moves required to reach 'E' from 'S'. If there is no valid path, output -1.

## sample
5
S....
.#...
..#..
.....
....E
8