#C10884. Maze Path Existence
Maze Path Existence
Maze Path Existence
You are given a maze represented as a grid of characters. Each cell in the maze is represented by one of the following characters:
S
- The starting point of the maze.D
- The destination point..
- An open cell that can be traversed.#
- A wall that cannot be traversed.
Your task is to determine whether there exists a path from the starting point S
to the destination D
by moving only in the four cardinal directions (up, down, left, right). Diagonal moves are not allowed.
The problem can be formulated using the following BFS (Breadth-First Search) approach:
Find S
and D
in the grid. Then, starting at S
, explore all reachable cells by moving in the four directions until either D
is reached or no more cells can be reached.
If there exists a path, print YES; otherwise, print NO.
Note: If any formula is required, use the LaTeX formatting. For instance, you may denote grid boundaries as \(0 \leq x < n\) and \(0 \leq y < m\).
inputFormat
The input is given via stdin and consists of:
- A single integer
n
on the first line, which denotes the number of rows in the maze. (\(1 \leq n \leq 100\)) - Followed by
n
lines, each containing a string of equal length that represents a row of the maze. All rows have the same number of characters \(m\) (\(1 \leq m \leq 100\)).
It is guaranteed that the maze contains exactly one S
and exactly one D
.
outputFormat
Output a single line to stdout:
- YES if a path exists from
S
toD
. - NO otherwise.
4
S....
.###.
.#D#.
...#.
YES