#K55872. Minimum Moves to Reach Target

    ID: 30072 Type: Default 1000ms 256MiB

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 and m representing the dimensions of the grid.
  • The next n lines each contain a string of length m with characters either . or #.
  • The following line contains four integers: x_start, y_start, x_end, and y_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.

## sample
1
1 1
.
0 0 0 0
0

</p>