#C7628. Minimum Moves to Reach the End of a Grid

    ID: 51520 Type: Default 1000ms 256MiB

Minimum Moves to Reach the End of a Grid

Minimum Moves to Reach the End of a Grid

This problem asks you to determine the minimum number of moves required to traverse a grid from the top-left cell to the bottom-right cell. The grid has dimensions \(n \times m\) and each cell is either free (denoted by .) or blocked (denoted by #). You may move in the four cardinal directions: up, down, left, and right.

Your task is to output the minimum number of moves needed to reach the target cell. If there is no valid path, output IMPOSSIBLE.

Note: The starting cell is at the top-left and the ending cell is at the bottom-right. The answer should be provided for each test case on a separate line.

The core idea is to use the Breadth-First Search (BFS) algorithm. In mathematical terms, if \(d(x, y)\) is the distance from the start to cell \((x,y)\), then the recurrence for free cells is:

\[ d(x, y) = \min_{(x', y') \in \mathcal{N}(x,y)}\{ d(x', y') \} + 1 \]

subject to the condition that \(d(0, 0) = 0\) and cells with obstacles are not visited.

inputFormat

The first line contains an integer \(T\) representing the number of test cases.

Each test case is described as follows:

  • The first line of each test case contains two integers \(n\) and \(m\) denoting the number of rows and columns of the grid.
  • The following \(n\) lines each contain a string of length \(m\) consisting only of the characters . and #, representing the grid.

Input is provided via standard input (stdin).

outputFormat

For each test case, output a single line containing the minimum number of moves required to travel from the top-left cell to the bottom-right cell. If no such path exists, output IMPOSSIBLE.

Output should be provided via standard output (stdout).

## sample
2
3 3
...
.#.
...
4 4
....
.##.
..#.
....
4

6

</p>