#C6056. Minimum Moves to Reach the Farm's Bottom-Right

    ID: 49774 Type: Default 1000ms 256MiB

Minimum Moves to Reach the Farm's Bottom-Right

Minimum Moves to Reach the Farm's Bottom-Right

You are given a farm represented as an n×mn \times m grid. Each cell in the grid is either open (denoted by '.') or blocked (denoted by '#'). A tractor is placed at the top-left corner of the grid, and your task is to determine the minimum number of moves required to get the tractor from the top-left cell to the bottom-right cell. Moves can only be made in the four cardinal directions: up, down, left, and right. If the starting cell or the destination cell is blocked, or if there is no valid path, return -1.

The number of cells in the grid is n×mn \times m, and a move consists of transitioning from one cell to an adjacent cell.

inputFormat

Input is read from standard input (stdin). The first line contains two integers nn and mm, representing the number of rows and columns respectively. This is followed by nn lines, each containing a string of length mm, where each character is either '.' (an open cell) or '#' (a blocked cell).

outputFormat

Output a single integer on standard output (stdout), which is the minimum number of moves needed to reach the bottom-right cell from the top-left cell. If it is impossible to reach the destination, output -1.## sample

5 6
#..#.#
##.#.#
#.##..
#....#
######
-1

</p>