#K346. Minimum Moves to Reach End

    ID: 25345 Type: Default 1000ms 256MiB

Minimum Moves to Reach End

Minimum Moves to Reach End

You are given an n×m grid representing a factory floor where each cell is either open (represented by '.') or blocked (represented by '#'). A robot starts at the top-left corner (cell (0,0)) and must reach the bottom-right corner (cell (n-1, m-1)). The robot can move one cell at a time in the four cardinal directions (up, down, left, right). Your task is to determine the minimum number of moves required for the robot to reach the destination. If the destination is unreachable, output -1.

Note: The starting and ending cells must be unblocked. The moves are counted as the number of steps taken.

Example:

For a grid of size 4×5:

...#.
.#.#.
.##..
.....

The minimum number of moves required is 7.

The answer should use a breadth-first search (BFS) approach. All formulas, if any, must be rendered in LaTeX format; though in this problem no explicit formulas are required.

inputFormat

The first line contains two integers n and m separated by a space, representing the number of rows and columns of the grid, respectively. This is followed by n lines each containing a string of length m consisting of the characters '.' and '#'.

You are to read the input from the standard input (stdin).

outputFormat

Output a single integer: the minimum number of moves required to reach the destination. If it is impossible to reach the destination, output -1.

The output should be written to the standard output (stdout).

## sample
4 5
...#.
.#.#.
.##..
.....
7