#K55872. Minimum Moves to Reach Target
Minimum Moves to Reach Target
Minimum Moves to Reach Target
You are given a grid with n rows and m columns. Each cell in the grid is either a free cell denoted by .
or an obstacle denoted by #
. You are also given the starting coordinates and the target coordinates. Your task is to determine the minimum number of moves required to reach the target cell from the starting cell using only four directions (up, down, left, right). If either the starting or the target cell is blocked, or the target cell is unreachable, output -1
.
Note: Moves are counted as steps taken from one cell to an adjacent cell, and cells with obstacles cannot be traversed. The problem can be solved using a breadth-first search (BFS) algorithm.
inputFormat
The input is read from stdin and has the following format:
T n m row_1 row_2 ... row_n x_start y_start x_end y_end ... (repeated for each of the T test cases)
Where:
T
is the number of test cases.- For each test case, the first line contains two integers
n
andm
representing the dimensions of the grid. - The next
n
lines each contain a string of lengthm
with characters either.
or#
. - The following line contains four integers:
x_start
,y_start
,x_end
, andy_end
denoting the starting and target cell coordinates (0-indexed).
outputFormat
For each test case, output on a new line a single integer representing the minimum number of moves required to reach the target cell from the starting cell. If the target cell is not reachable or if either the starting or target cell is blocked, output -1
.
1
1 1
.
0 0 0 0
0
</p>