#K39662. Minimum Moves to Reach End in a Grid

    ID: 26471 Type: Default 1000ms 256MiB

Minimum Moves to Reach End in a Grid

Minimum Moves to Reach End in a Grid

Given an \(n \times m\) grid where each cell is either . (open) or # (blocked), you need to move from the top-left corner to the bottom-right corner. You can only move right or down at each step. Your task is to determine the minimum number of moves required to reach the destination. If the start or end cell is blocked, or if no valid path exists, output -1.

inputFormat

The input begins with a line containing two space-separated integers (n) and (m), representing the number of rows and columns of the grid respectively. The following (n) lines each contain a string of length (m), where each character is either . (an open cell) or # (a blocked cell).

outputFormat

Output a single integer: the minimum number of moves needed to reach the bottom-right corner from the top-left corner using only right and down moves. If no valid path exists, output -1.## sample

5 5
.....
.#...
.##..
...#.
.....
8