#C7594. Shortest Path in a Maze

    ID: 51482 Type: Default 1000ms 256MiB

Shortest Path in a Maze

Shortest Path in a Maze

You are given a maze represented as a grid of characters. The maze contains the following symbols:

  • S: the starting cell
  • E: the ending cell
  • .: an open cell that you can traverse
  • #: a wall that you cannot pass

Your task is to compute the shortest number of moves required to go from the starting cell SS to the ending cell EE. You may move in the four cardinal directions: up, down, left, and right. If there is no valid path, output -1.

The problem can be modeled using the Breadth-First Search (BFS) algorithm on a grid. The distance or number of moves is defined as the count of steps taken from one cell directly adjacent (in one of the four directions) to the next.

inputFormat

The input is provided via standard input (stdin). The first line contains two integers nn and mm, where nn is the number of rows and mm is the number of columns in the maze. Each of the following nn lines contains a string of length mm representing one row of the maze. The characters will be one of: '.', '#', 'S', or 'E'.

outputFormat

Output a single integer on standard output (stdout): the minimum number of moves required to reach the end cell EE from the start cell SS. If no path exists, output -1.## sample

5 7
.......
.#.#.#.
.#S#E#.
.#.#.#.
.......
6