#C979. Maze Shortest Path

    ID: 53921 Type: Default 1000ms 256MiB

Maze Shortest Path

Maze Shortest Path

You are given a maze represented as an N x M grid, where each cell is one of the following characters:

  • 'S': The starting point.
  • 'E': The exit point.
  • '.': An open path.
  • '#': A wall.

Your task is to compute the length of the shortest path from 'S' to 'E'. Movement is only permitted in the four cardinal directions (up, down, left, right). If there is no valid path, output -1.

Note: The maze is given as multiple test cases. Each test case starts with two integers n and m followed by n lines representing the maze. The input ends with a test case where n = 0 and m = 0.

inputFormat

The input consists of multiple test cases. Each test case begins with a line containing two integers n and m (the number of rows and columns respectively). This is followed by n lines, each containing a string of length m that represents a row of the maze. The input terminates with a line containing "0 0" which should not be processed.

outputFormat

For each test case, output a single line with one integer: the minimum number of moves required to travel from 'S' to 'E'. If there is no valid path, output -1.## sample

5 5
S....
.###.
...#.
.#...
...E.
0 0
7