VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-moves-required-to-come-out-of-a-grid-safely/

⇱ Minimum moves required to come out of a grid safely - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum moves required to come out of a grid safely

Last Updated : 23 Jul, 2025

Given a grid mat[][] of size M * N, consisting of only 0s, 1s, and 2s, where 0 represents empty place, 1 represents a person and 2 represents the fire, the task is to count the minimum number of moves required such that the person comes out from the grid safely. In each step, the fire will burn its side-adjacent cells and the person will move from the current cell to one of its side-adjacent cells. If it is not possible to come out from the grid, then print -1.

Note: A person will come out from the grid if the person reaches one of the border sides of the grid.

Examples:

Input: mat[][] = { { 0, 0, 0, 0 }, { 2, 0, 0, 0 }, { 2, 1, 0, 0 }, { 2, 2, 0, 0 } } 
Output:
Explanation: 
Possible moves of the person are (2, 1) ? (2, 2) ? (2, 3). 
The person reaches one of the border sides of the grid(last row) in 2 moves and also it is the minimum possible count. 
Therefore, the required output is 2.

Input: mat[][] = { { 0, 2, 0, 0 }, { 2, 1, 0, 2 }, { 2, 0, 0, 0 }, { 2, 0, 2, 0 }} 
Output: -1

Approach: The problem can be solved using concepts to solve the problem Rotten Oranges. The idea is to perform BFS on the spreading fire as well as the moves of the person. Follow the steps below to solve the problem:

  1. Initialize two empty queues fQ and pQ, to store the cellsin which the fire can spread and the person can move to, respectively.
  2. Initialize a 2D array, say visited[][], to check if the cell (i, j) is already visited by the person or not.
  3. Enqueue all the side-adjacent cells of the person and mark all the adjacent cells as visited cell.
  4. Enqueue all the side-adjacent cells of the fire cells into fQ and mark all the side-adjacent cells as burning cells.
  5. Initialize a variable, say depth, to keep track of the shortest distance between two cells.
  6. Perform the following steps while pQ is not empty: 
    • Increment the depth by 1.
    • Dequeue all cells from pQ and enqueue all the valid side-adjacent cells of the popped cell.
    • If any adjacent cell enqueued is present at border of the grid, then print the value of depth.
    • Otherwise, dequeue all the cells from fQ. For each popped cell, enqueue all the valid adjacent cells.
  7. From the above steps, if it is not possible to come out from the grid, then print -1.

Below is the implementation of above approach:


Output: 
2

 

Time Complexity: O(N * M)
Auxiliary Space: O(N * M)

Comment