Problems > Escape the Maze

Escape the Maze

Difficulty: 1400 4000 ms 128 MB

bfs graphs

Walk from S to T through free cells (.), avoiding walls (#), moving in the four cardinal directions. Print the fewest steps, or −1.

Input: the first line has N and M; the next N lines each have M characters. Exactly one S and one T exist.

Output: the shortest number of steps, or −1.

Constraints:

  • 2 ≤ N, M ≤ 500

Sample Tests

Input 1
3 3
S.#
.#.
..T
Output 1
4
Input 2
2 2
S#
#T
Output 2
-1

Read the Editorial

Discussion (opens after you solve — no spoilers before)

No comments yet.

Submit Your Solution

Log in or create a free account to run and submit code.