#K53357. Shortest Path in a Grid
Shortest Path in a Grid
Shortest Path in a Grid
You are given a 2D grid of integers where each cell is either 0
(passable) or 1
(impassable). Your task is to find the shortest path from the start position to the target position using only orthogonal moves (up, down, left, right).
The grid is represented by n rows and m columns. If a path exists, output the minimum number of steps required; otherwise, output -1
.
The moves are allowed only between adjacent cells (not diagonally) and you cannot move into or cross an impassable cell (1
).
Note: The start and target positions are given in 0-indexed format.
Mathematically, if we denote grid coordinates as \((i,j)\) for \(0 \leq i < n\) and \(0 \leq j < m\), and define valid moves: \[ (i,j) \to (i-1,j),\quad (i,j) \to (i+1,j),\quad (i,j) \to (i,j-1),\quad (i,j) \to (i,j+1), \] find the minimum number of such moves to reach the target or return \(-1\) if unreachable.
inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains two space-separated integers n and m, the number of rows and columns in the grid.
- The next n lines each contain m space-separated integers (each either 0 or 1), representing the grid.
- The following line contains two integers indicating the start position: the row and column indices.
- The last line contains two integers indicating the target position: the row and column indices.
All indices are 0-indexed.
outputFormat
Output a single integer to standard output (stdout): the minimum number of steps required to reach the target. If the target is unreachable, output -1
.
5 5
0 0 1 0 0
0 0 0 0 1
1 0 1 0 0
0 0 0 1 0
0 1 0 0 0
0 0
4 4
8