#C1214. Minimum Moves to Reach Destination
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:
- The first line contains an integer n representing the size of the grid.
- 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
.
5
S....
.#...
..#..
.....
....E
8