Escape from grid

4.1

16 votes
Algorithms, Breadth First Search, Graphs, Medium
Problem

Assume that you are given a two-dimensional grid  that contains  rows and columns. The grid consists of only three integers (, , and ).

  • denotes an empty cell
  • denotes that a cell contains a plant
  • denotes a cell where you are standing initially

You can move into an adjacent cell if that adjacent cell is empty. Two cells are adjacent if they share a side. In other words, if a cell is empty, then you can move in one of the four directions, Up, Down, Left, and Right.
You cannot move out of the grid .

Your task is to find the length of the shortest path to reach one of the boundary edges of the grid without stepping on a plant. The length of a path is equal to the number of moves you make.

Note: It is guaranteed that there is only one cell with value (you are standing in only one cell initially).

Input format

  • First line: Two space-separated integers, and , denoting the number of rows and columns in the grid respectively
  • Next lines:  space-separated integers denoting the rows of the grid

Output format

Print the length of the shortest path to reach one of the boundary edges of the grid without stepping on a plant. If it is not possible to reach the edge of the grid, then print .

Constraints

where denotes a cell of the  grid

Sample Input
4 5
1 1 1 0 1
1 0 2 0 1
0 0 1 0 1
1 0 1 1 0
Sample Output
2
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

There are 4 rows and 5 columns in the grid.

1 1 1 0 1
1 0 2 0 1
0 0 1 0 1
1 0 1 1 0

Initially, you are standing at cell (second row and third column) denoted by 2. There are three ways to reach an boundary edge of the grid without stepping on a plant.

  • Move to cell (Left), then move to cell (Down) and then move to cell (Down) (3 steps).
  • Move to cell (Left), then move to cell (Down) and then move to cell (Left) (3 steps).
  • Move to cell (Right) and then move to cell (Up) (2 steps).

In the third step, we took only 2 steps to reach to the edge of the grid which is the shortest path.

Editor Image

?