#K81757. Shortest Path in a Grid with Obstacles

    ID: 35824 Type: Default 1000ms 256MiB

Shortest Path in a Grid with Obstacles

Shortest Path in a Grid with Obstacles

You are given a grid of size \( N \times N \) where each cell is identified by its row and column numbers (1-indexed). A robot starts at a given cell and must reach a target cell by moving one step at a time in one of four directions (up, down, left, right). Some cells contain obstacles, and the robot cannot enter these cells.

Your task is to compute the minimum number of moves required for the robot to reach the target cell. If the target cell is unreachable, output \( -1 \). Note that if the starting cell is the same as the target cell, then the required moves is \( 0 \).

The allowed movement directions can be represented by the vectors \( (\Delta x, \Delta y) \) where \( (\Delta x, \Delta y) \in \{ (-1,0), (1,0), (0,-1), (0,1) \} \).

inputFormat

The input is given via standard input (stdin) as follows:

  • The first line contains an integer \( N \) (the size of the grid, i.e. the grid has \( N \) rows and \( N \) columns).
  • The second line contains two space-separated integers \( s_x \) and \( s_y \) representing the starting cell's coordinates (row and column).
  • The third line contains two space-separated integers \( e_x \) and \( e_y \) representing the target cell's coordinates.
  • The fourth line contains an integer \( M \) denoting the number of obstacles.
  • Each of the following \( M \) lines contains two space-separated integers representing the coordinates (row and column) of an obstacle.

All coordinates are 1-indexed.

outputFormat

Output a single integer to standard output (stdout) representing the minimum number of moves required for the robot to reach the target cell. If the target is unreachable, output \( -1 \).

## sample
5
1 1
5 5
3
3 3
3 4
2 3
8

</p>