#C11356. Minimum Cost Path in a Grid

    ID: 40663 Type: Default 1000ms 256MiB

Minimum Cost Path in a Grid

Minimum Cost Path in a Grid

You are given an n x n grid where each cell is either open or blocked, represented by a character: '.' denotes an open cell and '#' denotes a blocked cell. Starting at the top-left corner, your goal is to reach the bottom-right corner using the minimum number of moves. You can move up, down, left, or right.

If we denote the current cell as \((i,j)\), then a move from \((i,j)\) to \((i',j')\) is valid if: \[ 0 \leq i', j' < n \quad \text{and} \quad grid[i'][j'] = '.' \]

Output the minimum number of moves required to reach the destination, or \(-1\) if it is impossible.

Note: The starting cell (top-left) and the destination (bottom-right) must be open for a path to exist.

inputFormat

The input is provided via standard input and has the following format:

n
row1
row2
...
rown

Where:

  • n is an integer representing the size of the grid.
  • Each of the next n lines is a string of length n containing only the characters '.' and '#'.

outputFormat

Output a single integer on standard output representing the minimum number of moves required to reach the destination. If no such path exists, output -1.

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