#K74472. Shortest Path in a Forest Grid
Shortest Path in a Forest Grid
Shortest Path in a Forest Grid
You are given a grid representing a forest. Each cell in the grid is either open (represented by '.') or blocked (represented by '#'). Your task is to find the length of the shortest path from the top-left corner \((1,1)\) to the bottom-right corner \((n,m)\) using only four possible moves: up, down, left, and right. If no such path exists, output -1.
Note: The input grid is provided as \(n\) rows of characters. Although the problem description uses 1-indexing for explanation, typical programming implementations use 0-indexing. An efficient approach to this problem is to use the Breadth-First Search (BFS) algorithm.
inputFormat
The first line consists of two integers \(n\) and \(m\) — the number of rows and columns of the grid, respectively. The next \(n\) lines each contain a string of length \(m\) representing a row of the grid, where each character is either '.' (open) or '#' (blocked).
outputFormat
Output a single integer which is the length of the shortest path from the top-left corner to the bottom-right corner. If no such path exists, output -1.
## sample5 5
...#.
..#..
#.##.
.....
.##..
9