#K78967. Minimum Steps to Reach Target in a Grid

    ID: 35204 Type: Default 1000ms 256MiB

Minimum Steps to Reach Target in a Grid

Minimum Steps to Reach Target in a Grid

You are given a warehouse represented by an n x m grid, where each cell can either be free (denoted by 0) or blocked by an obstacle (denoted by 1). A robot starts at a given position \( (sr, sc) \) and needs to reach a target position \( (tr, tc) \). The robot can move one step at a time in the four cardinal directions: up, down, left, and right.

Your task is to compute the minimum number of steps required to reach the target cell. If the target cell is unreachable due to obstacles, output \( -1 \). If the starting position is the same as the target, the answer is \( 0 \).

This problem can be solved using the Breadth-First Search (BFS) algorithm, which ensures the shortest path is found.

inputFormat

The input is read from \( stdin \) and has the following format:

  • The first line contains two integers \( n \) and \( m \), representing the number of rows and columns of the grid.
  • The second line contains two integers \( sr \) and \( sc \), representing the starting row and column of the robot.
  • The third line contains two integers \( tr \) and \( tc \), representing the target row and column.
  • The next \( n \) lines each contain \( m \) space-separated integers (either 0 or 1), representing the grid.

outputFormat

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

## sample
5 5
0 0
4 4
0 0 0 0 0
0 1 1 1 0
0 1 0 0 0
0 1 1 1 0
0 0 0 0 0
8