#K38962. Find Path in a Grid
Find Path in a Grid
Find Path in a Grid
You are given a grid represented by a 2D matrix of integers where each cell can either be walkable (represented by 0) or blocked by a wall (represented by 1). Your task is to determine whether there exists a path from a starting cell to an ending cell using only adjacent moves (up, down, left, right).
The problem can be modeled as finding a path on a grid graph. Note that a move from cell \( (x, y) \) to an adjacent cell is allowed only if the target cell is within the grid bounds and is walkable.
For example, given the grid below:
[ \begin{matrix} 0 & 0 & 1 & 0 \ 0 & 1 & 0 & 0 \ 0 & 0 & 0 & 1 \ 0 & 1 & 0 & 0 \end{matrix} ]
and starting position \( (0, 0) \) and ending position \( (3, 3) \), a valid path exists. However, if the grid is modified such that the obstacles block the path, then no valid path can be found.
inputFormat
The input is given via stdin with the following format:
R C row1 row2 ... rowR start_x start_y end_x end_y
Where:
- R and C are integers denoting the number of rows and columns in the grid.
- Each of the next R lines contains C integers (0 or 1) separated by spaces representing the grid.
- \(start_x\) and \(start_y\) specify the starting coordinates (0-indexed).
- \(end_x\) and \(end_y\) specify the target coordinates (0-indexed).
outputFormat
Output a single line to stdout:
- Print
YES
if there exists a path from the starting position to the ending position, otherwise printNO
.
4 4
0 0 1 0
0 1 0 0
0 0 0 1
0 1 0 0
0 0
3 3
YES
</p>