#K48812. Minimum Moves in Grid
Minimum Moves in Grid
Minimum Moves in Grid
You are given a grid with n rows and m columns. Each cell in the grid is either free (denoted by .
) or blocked (denoted by #
). The grid uses 1-indexed coordinates. Starting from the cell at position (sr, sc), your task is to determine the minimum number of moves required to reach the target cell (tr, tc).
You can move in four directions: up, down, left, or right. Moves can only be made to adjacent cells that are free. If the target cell is unreachable, output -1
.
This problem is typically solved by modeling the grid as an unweighted graph and performing a breadth-first search (BFS) to find the shortest path.
inputFormat
The input is read from standard input (stdin) in the following format:
- The first line contains two integers n and m, representing the number of rows and columns in the grid.
- The second line contains four integers: sr, sc, tr, and tc, which are the 1-indexed starting row, starting column, target row, and target column respectively.
- The next n lines each contain a string of length m consisting of characters
.
and#
, representing the grid layout.
outputFormat
Output a single integer to standard output (stdout) — the minimum number of moves required to reach the target cell if it is reachable, or -1
if it is not.
5 5
1 1 5 5
.....
.#.#.
.....
.#.#.
.....
8