#K146. Shortest Path in a Grid
Shortest Path in a Grid
Shortest Path in a Grid
You are given an n × m grid where each cell is either passable (denoted by '.') or blocked (denoted by '#'). Your task is to find the length of the shortest path from a starting coordinate (sx, sy) to a destination coordinate (ex, ey), moving only in the four cardinal directions (up, down, left, right).
The rules are as follows:
- You can move only to adjacent cells if they are within bounds and passable.
- If the start and destination cells are the same, the shortest path length is 0.
- If there is no valid path from start to destination, output -1.
Note: The grid indices start from 0.
The solution should use breadth-first search (BFS) to compute the shortest distance.
inputFormat
The input is given via stdin and consists of the following:
- The first line contains two integers n and m representing the number of rows and columns.
- The next n lines each contain a string of length m representing the grid.
- The last line contains four integers sx, sy, ex, ey representing the starting and ending cell coordinates respectively.
outputFormat
Output a single integer via stdout representing the length of the shortest path. If no such path exists, output -1.
## sample5 5
.....
.###.
...#.
.#...
.....
0 0 4 4
8