Minimum steps to reach any of the boundary edges of a matrix | Set-2

Given an N X M matrix, where ai, j = 1 denotes the cell is not empty, ai, j = 0 denotes the cell is empty and ai, j = 2, denotes that you are standing at that cell. You can move vertically up or down and horizontally left or right to any cell which is empty. The task is to find the minimum number of steps to reach any boundary edge of the matrix. Print -1 if not possible to reach any of the boundary edges.Â
Note: There will be only one cell with value 2 in the entire matrix.Â
Examples:
Input: matrix[] = {1, 1, 1, 0, 1}
{1, 0, 2, 0, 1}
{0, 0, 1, 0, 1}
{1, 0, 1, 1, 0}
Output: 2
Move to the right and then move
upwards to reach the nearest boundary
edge.
Input: matrix[] = {1, 1, 1, 1, 1}
{1, 0, 2, 0, 1}
{1, 0, 1, 0, 1}
{1, 1, 1, 1, 1}
Output: -1
Approach: The problem has been solved in Set-1 using Dynamic Programming. In this article, we will be discussing a method using BFS. Given below are the steps to solve the above problem.
- Find the index of the ‘2’ in the matrix.
- Check if this index is a boundary edge or not, if it is, then no moves are required.
- Insert the index x and index y of ‘2’ in the queue with moves as 0.
- Use a 2-D vis array to mark the visiting positions in the matrix.
- Iterate till the queue is empty or we reach any boundary edge.
- Get the front element(x, y, val = moves) in the queue and mark vis[x][y] as visited. Do all the possible moves(right, left, up and down) possible.
- Re-insert val+1 and their indexes of all the valid moves to the queue.
- If the x and y become the boundary edges any time return val.
- If all the moves are made, and the queue is empty, then it is not possible, hence return -1.
Below is the implementation of the above approach:Â
CPP
// C++ program to find Minimum steps// to reach any of the boundary// edges of a matrix#include <bits/stdc++.h>using namespace std;#define r 4#define c 5Â
// Function to check validitybool check(int i, int j, int n, int m, int mat[r]){Â Â Â Â if (i >= 0 && i < n && j >= 0 && j < m) {Â Â Â Â Â Â Â Â if (mat[i][j] == 0)Â Â Â Â Â Â Â Â Â Â Â Â return true;Â Â Â Â }Â Â Â Â return false;}Â
// Function to find out minimum stepsint findMinSteps(int mat[r], int n, int m){Â
    int indx, indy;    indx = indy = -1;Â
    // Find index of only 2 in matrix    for (int i = 0; i < n; i++) {        for (int j = 0; j < m; j++) {            if (mat[i][j] == 2) {                indx = i, indy = j;                break;            }        }        if (indx != -1)            break;    }Â
    // Push elements in the queue    queue<pair<int, pair<int, int> > > q;Â
    // Push the position 2 with moves as 0    q.push(make_pair(0, make_pair(indx, indy)));Â
    // If already at boundary edge    if (check(indx, indy, n, m, mat))        return 0;Â
    // Marks the visit    bool vis[r];    memset(vis, 0, sizeof vis);Â
    // Iterate in the queue    while (!q.empty()) {        // Get the front of the queue        auto it = q.front();Â
        // Pop the first element from the queue        q.pop();Â
        // Get the position        int x = it.second.first;        int y = it.second.second;Â
        // Moves        int val = it.first;Â
        // If a boundary edge        if (x == 0 || x == (n - 1) || y == 0 || y == (m - 1)) {            return val;        }Â
        // Marks the visited array        vis[x][y] = 1;Â
        // If a move is possible        if (check(x - 1, y, n, m, mat)) {Â
            // If not visited previously            if (!vis[x - 1][y])                q.push(make_pair(val + 1, make_pair(x - 1, y)));        }Â
        // If a move is possible        if (check(x + 1, y, n, m, mat)) {Â
            // If not visited previously            if (!vis[x + 1][y])                q.push(make_pair(val + 1, make_pair(x + 1, y)));        }Â
        // If a move is possible        if (check(x, y + 1, n, m, mat)) {Â
            // If not visited previously            if (!vis[x][y + 1])                q.push(make_pair(val + 1, make_pair(x, y + 1)));        }Â
        // If a move is possible        if (check(x, y - 1, n, m, mat)) {Â
            // If not visited previously            if (!vis[x][y - 1])                q.push(make_pair(val + 1, make_pair(x, y - 1)));        }    }Â
    return -1;}Â
// Driver Codeint main(){    int mat[r] = { { 1, 1, 1, 0, 1 },                      { 1, 0, 2, 0, 1 },                      { 0, 0, 1, 0, 1 },                      { 1, 0, 1, 1, 0 } };Â
    cout << findMinSteps(mat, r, c);} |
Java
// Java program to find Minimum steps// to reach any of the boundary// edges of a matriximport java.util.*;Â
class GFG {Â
  public static final int R = 4;  public static final int C = 5;Â
  // Function to check validity  public static boolean check(int i, int j, int n, int m,                              int[][] mat)  {    if (i >= 0 && i < n && j >= 0 && j < m) {      if (mat[i][j] == 0) {        return true;      }    }    return false;  }Â
  // Function to find out minimum steps  public static int findMinSteps(int[][] mat, int n,                                 int m)  {Â
    int indx, indy;    indx = indy = -1;Â
    // Find index of only 2 in matrix    for (int i = 0; i < n; i++) {      for (int j = 0; j < m; j++) {        if (mat[i][j] == 2) {          indx = i;          indy = j;          break;        }      }      if (indx != -1) {        break;      }    }Â
    // Push elements in the queue    Queue<int[]> q = new LinkedList<int[]>();Â
    // Push the position 2 with moves as 0    q.add(new int[] { indx, indy, 0 });Â
    // If already at boundary edge    if (check(indx, indy, n, m, mat)) {      return 0;    }Â
    // Marks the visit    boolean[][] vis = new boolean[n][m];Â
    // Iterate in the queue    while (!q.isEmpty()) {Â
      // Pop the first element from the queue      int[] curr = q.poll();Â
      // Get the position      int x = curr[0];      int y = curr[1];      int val = curr[2];Â
      // If a boundary edge      if (x == 0 || x == (n - 1) || y == 0          || y == (m - 1)) {        return val;      }Â
      // Marks the visited array      vis[x][y] = true;Â
      // If a move is possible towards up      if (check(x - 1, y, n, m, mat)) {Â
        // If not visited previously        if (!vis[x - 1][y]) {          q.add(new int[] { x - 1, y, val + 1 });        }      }Â
      // If a move is possible towards down      if (check(x + 1, y, n, m, mat)) {Â
        // If not visited previously        if (!vis[x + 1][y]) {          q.add(new int[] { x + 1, y, val + 1 });        }      }Â
      // If a move is possible towards right      if (check(x, y + 1, n, m, mat)) {Â
        // If not visited previously        if (!vis[x][y + 1]) {          q.add(new int[] { x, y + 1, val + 1 });        }      }Â
      // If a move is possible towards left      if (check(x, y - 1, n, m, mat)) {Â
        // If not visited previously        if (!vis[x][y - 1]) {          q.add(new int[] { x, y - 1, val + 1 });        }      }    }    return -1;  }Â
  // Driver Code  public static void main(String[] args)  {    int[][] mat = { { 1, 1, 1, 0, 1 },                   { 1, 0, 2, 0, 1 },                   { 0, 0, 1, 0, 1 },                   { 1, 0, 1, 1, 0 } };    System.out.println(findMinSteps(mat, R, C));  }}Â
// This code is contributed by Prasad Kandekar(prasad264) |
Python3
# Python3 program to find Minimum steps# to reach any of the boundary# edges of a matrixfrom collections import dequer = 4c = 5Â
# Function to check validitydef check(i, j, n, m, mat):Â
    if (i >= 0 and i < n and j >= 0 and j < m):        if (mat[i][j] == 0):            return TrueÂ
    return FalseÂ
# Function to find out minimum stepsdef findMinSteps(mat, n, m):Â
    indx = indy = -1;Â
    # Find index of only 2 in matrix    for i in range(n):        for j in range(m):            if (mat[i][j] == 2):                indx = i                indy = j                breakÂ
        if (indx != -1):            breakÂ
    # Push elements in the queue    q = deque()Â
    # Push the position 2 with moves as 0    q.append([0, indx, indy])Â
    # If already at boundary edge    if (check(indx, indy, n, m, mat)):        return 0Â
    # Marks the visit    vis=[ [0 for i in range(r)]for i in range(r)]Â
    # Iterate in the queue    while len(q) > 0:                 # Get the front of the queue        it = q.popleft()Â
        #Pop the first element from the queueÂ
        # Get the position        x = it[1]        y = it[2]Â
        # Moves        val = it[0]Â
        # If a boundary edge        if (x == 0 or x == (n - 1) or y == 0 or y == (m - 1)):            return valÂ
Â
        # Marks the visited array        vis[x][y] = 1Â
        # If a move is possible        if (check(x - 1, y, n, m, mat)):Â
            # If not visited previously            if (not vis[x - 1][y]):                q.append([val + 1, x - 1, y])Â
        # If a move is possible        if (check(x + 1, y, n, m, mat)):Â
            # If not visited previously            if (not vis[x + 1][y]):                q.append([val + 1, x + 1, y])Â
        # If a move is possible        if (check(x, y + 1, n, m, mat)):Â
            # If not visited previously            if (not vis[x][y + 1]):                q.append([val + 1, x, y + 1])Â
        # If a move is possible        if (check(x, y - 1, n, m, mat)):Â
            # If not visited previously            if (not vis[x][y - 1]):                q.append([val + 1, x, y - 1])Â
    return -1Â
# Driver Codemat = [[1, 1, 1, 0, 1 ],       [1, 0, 2, 0, 1 ],       [0, 0, 1, 0, 1 ],       [1, 0, 1, 1, 0 ] ];Â
print(findMinSteps(mat, r, c))Â
# This code is contributed by mohit kumar 29 |
C#
// C# program to find Minimum steps// to reach any of the boundary// edges of a matrixusing System;using System.Collections.Generic;Â
public class GFG {Â Â public static readonly int R = 4;Â Â public static readonly int C = 5;Â
  // Function to check validity  public static bool Check(int i, int j, int n, int m,                           int[, ] mat)  {    if (i >= 0 && i < n && j >= 0 && j < m) {      if (mat[i, j] == 0) {        return true;      }    }    return false;  }Â
  // Function to find out minimum steps  public static int findMinSteps(int[, ] mat, int n,                                 int m)  {    int indx, indy;    indx = indy = -1;Â
    // Find index of only 2 in matrix    for (int i = 0; i < n; i++) {      for (int j = 0; j < m; j++) {        if (mat[i, j] == 2) {          indx = i;          indy = j;          break;        }      }      if (indx != -1) {        break;      }    }Â
    // Push elements in the queue    Queue<int[]> q = new Queue<int[]>();Â
    // Push the position 2 with moves as 0    q.Enqueue(new int[] { indx, indy, 0 });Â
    // If already at boundary edge    if (Check(indx, indy, n, m, mat)) {      return 0;    }Â
    // Marks the visit    bool[, ] vis = new bool[n, m];Â
    // Iterate in the queue    while (q.Count != 0) {Â
      // Get the front of the queue      int[] curr = q.Dequeue();Â
      // Get the position      int x = curr[0];      int y = curr[1];Â
      // Moves      int val = curr[2];Â
      // If a boundary edge      if (x == 0 || x == (n - 1) || y == 0          || y == (m - 1)) {        return val;      }Â
      // Marks the visited array      vis[x, y] = true;Â
      // If a move is possible      if (Check(x - 1, y, n, m, mat)) {Â
        // If not visited previously        if (!vis[x - 1, y]) {          q.Enqueue(            new int[] { x - 1, y, val + 1 });        }      }Â
      // If a move is possible      if (Check(x + 1, y, n, m, mat)) {Â
        // If not visited previously        if (!vis[x + 1, y]) {          q.Enqueue(            new int[] { x + 1, y, val + 1 });        }      }Â
      // If a move is possible      if (Check(x, y + 1, n, m, mat)) {Â
        // If not visited previously        if (!vis[x, y + 1]) {          q.Enqueue(            new int[] { x, y + 1, val + 1 });        }      }Â
      // If a move is possible      if (Check(x, y - 1, n, m, mat)) {Â
        // If not visited previously        if (!vis[x, y - 1]) {          q.Enqueue(            new int[] { x, y - 1, val + 1 });        }      }    }    return -1;  }Â
  // Driver Code  static public void Main(string[] args)  {    int[, ] mat = { { 1, 1, 1, 0, 1 },                   { 1, 0, 2, 0, 1 },                   { 0, 0, 1, 0, 1 },                   { 1, 0, 1, 1, 0 } };Â
    Console.WriteLine(findMinSteps(mat, 4, 5));  }}Â
// This code is contributed by Prasad Kandekar(prasad264) |
Javascript
<script>Â
// JavaScript program to find Minimum steps// to reach any of the boundary// edges of a matrixconst r = 4const c = 5Â
// Function to check validityfunction check(i, j, n, m, mat){Â
    if (i >= 0 && i < n && j >= 0 && j < m){        if (mat[i][j] == 0)            return true    }Â
    return falseÂ
}Â
// Function to find out minimum stepsfunction findMinSteps(mat, n, m){Â
    let indx = -1, indy = -1;Â
    // Find index of only 2 in matrix    for(let i=0;i<n;i++){        for(let j=0;j<m;j++){            if (mat[i][j] == 2){                indx = i                indy = j                break            }        }        if (indx != -1){            break        }    }Â
    // Push elements in the queue    let q = []Â
    // Push the position 2 with moves as 0    q.push([0, indx, indy])Â
    // If already at boundary edge    if (check(indx, indy, n, m, mat))        return 0Â
    // Marks the visit    let vis = new Array(r);    for(let i=0;i<r;i++){        vis[i] = new Array(r).fill(0);    }Â
    // Iterate in the queue    while(q.length > 0){                 // Get the front of the queue        let it = q.shift()Â
        //Pop the first element from the queueÂ
        // Get the position        let x = it[1]        let y = it[2]Â
        // Moves        let val = it[0]Â
        // If a boundary edge        if (x == 0 || x == (n - 1) || y == 0 || y == (m - 1))            return valÂ
Â
        // Marks the visited array        vis[x][y] = 1Â
        // If a move is possible        if (check(x - 1, y, n, m, mat)){Â
            // If not visited previously            if (vis[x - 1][y] == 0)                q.push([val + 1, x - 1, y])        }Â
        // If a move is possible        if (check(x + 1, y, n, m, mat)){Â
            // If not visited previously            if (vis[x + 1][y] == 0)                q.push([val + 1, x + 1, y])        }Â
        // If a move is possible        if (check(x, y + 1, n, m, mat)){Â
            // If not visited previously            if (vis[x][y + 1] == 0)                q.push([val + 1, x, y + 1])        }Â
        // If a move is possible        if (check(x, y - 1, n, m, mat)){Â
            // If not visited previously            if (vis[x][y - 1] == 0)                q.push([val + 1, x, y - 1])        }    }Â
    return -1}Â
// Driver CodeÂ
let mat = [[1, 1, 1, 0, 1 ],    [1, 0, 2, 0, 1 ],    [0, 0, 1, 0, 1 ],    [1, 0, 1, 1, 0 ]];Â
document.write(findMinSteps(mat, r, c))Â
// This code is contributed by shinjanpatraÂ
</script> |
2
Complexity Analysis:
- Time Complexity: O(N^2)Â
- Auxiliary Space: O(N^2)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


