#K2336. Minimum Moves in a Maze
Minimum Moves in a Maze
Minimum Moves in a Maze
You are given a maze represented as an n x m grid. Each cell of the maze is either open (0
) or a wall (1
). You start at the top-left corner (i.e. cell (0, 0)) and your goal is to reach the bottom-right corner (i.e. cell (n-1, m-1)). You are allowed to move in four directions: up, down, left, or right.
The task is to determine the minimum number of moves required to reach the destination. If the destination cannot be reached, output -1
.
The movement condition can be formally represented as follows:
$$\text{allowed move: } (i, j) \to (i+dx, j+dy), \quad \text{where } (dx, dy) \in \{(-1, 0), (1, 0), (0, -1), (0, 1)\}$$
Note that if either the start cell or the destination cell is a wall, the answer is immediately -1
.
inputFormat
The first line contains two integers n
and m
representing the number of rows and columns of the maze, respectively.
This is followed by n
lines, each containing m
integers (either 0 or 1) separated by spaces, describing the maze.
outputFormat
Output a single integer which is the minimum number of moves required to travel from the top-left to the bottom-right corner of the maze. If it is impossible to reach the destination, output -1
.
3 3
0 1 0
0 0 0
1 0 0
4