Open In App

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

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 a value of 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 can be solved using a Dynamic Programming approach. Given below is the algorithm to solve the above problem. 

  • Find the position which has ‘2’ in the matrix.
  • Initialize two 2-D arrays of size the same as the matrix. The dp[][] which stores the minimum number of steps to reach any index i, j and vis[][] marks if any particular i, j position has been visited or not previously.
  • Call the recursive function which has the base case as follows: 
    1. if the traversal at any point reaches any of the boundary edges return 0.
    2. if the position of the points n, m has stored the minimum number of steps previously, then return dp[n][m].
  • Call the recursion again with all possible four moves that can be done from the position n, m. The moves are only possible if mat[n][m] is 0 and the position has not been visited previously.
  • Store the minimal of the four moves.
  • If the recursion returns any value less than 1e9, which we had stored as the maximum value, then there is an answer, else it does not have an answer.

Below is the implementation of the above approach: 

C++




// 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 col 5
 
// Function to find out minimum steps
int findMinSteps(int mat[r][col], int n, int m, int dp[r][col], bool vis[r][col])
{
    // boundary edges reached
    if (n == 0 || m == 0 || n == (r - 1) || m == (col - 1)) {
        return 0;
    }
 
    // already had a route through this
    // point, hence no need to re-visit
    if (dp[n][m] != -1)
        return dp[n][m];
 
    // visiting a position
    vis[n][m] = true;
 
    int ans1, ans2, ans3, ans4;
 
    ans1 = ans2 = ans3 = ans4 = 1e9;
 
    // vertically up
    if (mat[n - 1][m] == 0) {
        if (!vis[n - 1][m])
            ans1 = 1 + findMinSteps(mat, n - 1, m, dp, vis);
    }
 
    // horizontally right
    if (mat[n][m + 1] == 0) {
        if (!vis[n][m + 1])
            ans2 = 1 + findMinSteps(mat, n, m + 1, dp, vis);
    }
 
    // horizontally left
    if (mat[n][m - 1] == 0) {
        if (!vis[n][m - 1])
            ans3 = 1 + findMinSteps(mat, n, m - 1, dp, vis);
    }
 
    // vertically down
    if (mat[n + 1][m] == 0) {
        if (!vis[n + 1][m])
            ans4 = 1 + findMinSteps(mat, n + 1, m, dp, vis);
    }
 
    // minimum of every path
    dp[n][m] = min(ans1, min(ans2, min(ans3, ans4)));
    return dp[n][m];
}
 
// Function that returns the minimum steps
int minimumSteps(int mat[r][col], int n, int m)
{
    // index to store the location at
    // which you are standing
    int twox = -1;
    int twoy = -1;
 
    // find '2' in the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (mat[i][j] == 2) {
                twox = i;
                twoy = j;
                break;
            }
        }
        if (twox != -1)
            break;
    }
 
    // Initialize dp matrix with -1
    int dp[r][col];
    memset(dp, -1, sizeof dp);
 
    // Initialize vis matrix with false
    bool vis[r][col];
    memset(vis, false, sizeof vis);
 
    // Call function to find out minimum steps
    // using memoization and recursion
    int res = findMinSteps(mat, twox, twoy, dp, vis);
 
    // if not possible
    if (res >= 1e9)
        return -1;
    else
        return res;
}
 
// Driver Code
int main()
{
    int mat[r][col] = { { 1, 1, 1, 0, 1 },
                      { 1, 0, 2, 0, 1 },
                      { 0, 0, 1, 0, 1 },
                      { 1, 0, 1, 1, 0 } };
 
    cout << minimumSteps(mat, r, col);
}


Java




// Java program to find Minimum steps
// to reach any of the boundary
// edges of a matrix
class Solution
{
static final int  r=4,c=5;
 
// Function to find out minimum steps
static int findMinSteps(int mat[][], int n, int m, int dp[][], boolean vis[][])
{
    // boundary edges reached
    if (n == 0 || m == 0 || n == (r - 1) || m == (c - 1)) {
        return 0;
    }
  
    // already had a route through this
    // point, hence no need to re-visit
    if (dp[n][m] != -1)
        return dp[n][m];
  
    // visiting a position
    vis[n][m] = true;
  
    int ans1, ans2, ans3, ans4;
  
    ans1 = ans2 = ans3 = ans4 = (int)1e9;
  
    // vertically up
    if (mat[n - 1][m] == 0) {
        if (!vis[n - 1][m])
            ans1 = 1 + findMinSteps(mat, n - 1, m, dp, vis);
    }
  
    // horizontally right
    if (mat[n][m + 1] == 0) {
        if (!vis[n][m + 1])
            ans2 = 1 + findMinSteps(mat, n, m + 1, dp, vis);
    }
  
    // horizontally left
    if (mat[n][m - 1] == 0) {
        if (!vis[n][m - 1])
            ans3 = 1 + findMinSteps(mat, n, m - 1, dp, vis);
    }
  
    // vertically down
    if (mat[n + 1][m] == 0) {
        if (!vis[n + 1][m])
            ans4 = 1 + findMinSteps(mat, n + 1, m, dp, vis);
    }
  
    // minimum of every path
    dp[n][m] = Math.min(ans1, Math.min(ans2, Math.min(ans3, ans4)));
    return dp[n][m];
}
  
// Function that returns the minimum steps
static int minimumSteps(int mat[][], int n, int m)
{
    // index to store the location at
    // which you are standing
    int twox = -1;
    int twoy = -1;
  
    // find '2' in the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (mat[i][j] == 2) {
                twox = i;
                twoy = j;
                break;
            }
        }
        if (twox != -1)
            break;
    }
  
    // Initialize dp matrix with -1
    int dp[][]=new int[r][r];
    for(int j=0;j<r;j++)
    for(int i=0;i<r;i++)dp[j][i]=-1;
  
    // Initialize vis matrix with false
    boolean vis[][]= new boolean[r][r];
    for(int j=0;j<r;j++)
    for(int i=0;i<r;i++)vis[j][i]=false;
  
    // Call function to find out minimum steps
    // using memoization and recursion
    int res = findMinSteps(mat, twox, twoy, dp, vis);
  
    // if not possible
    if (res >= 1e9)
        return -1;
    else
        return res;
}
  
// 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( minimumSteps(mat, r, c));
}
}
//contributed by Arnab Kundu


Python




# Python program to find Minimum steps
# to reach any of the boundary
# edges of a matrix
 
r=4
col=5
  
# Function to find out minimum steps
def findMinSteps(mat, n, m, dp,vis):
 
    # boundary edges reached
    if (n == 0 or m == 0 or n == (r - 1) or m == (col - 1)):
        return 0
     
  
    # already had a route through this
    # point, hence no need to re-visit
    if (dp[n][m] != -1):
        return dp[n][m]
  
    # visiting a position
    vis[n][m] = True
  
    ans1, ans2, ans3, ans4=10**9,10**9,10**9,10**9
 
  
    # vertically up
    if (mat[n - 1][m] == 0):
        if (vis[n - 1][m]==False):
            ans1 = 1 + findMinSteps(mat, n - 1, m, dp, vis)
     
  
    # horizontally right
    if (mat[n][m + 1] == 0):
        if (vis[n][m + 1]==False):
            ans2 = 1 + findMinSteps(mat, n, m + 1, dp, vis)
     
  
    # horizontally left
    if (mat[n][m - 1] == 0):
        if (vis[n][m - 1]==False):
            ans3 = 1 + findMinSteps(mat, n, m - 1, dp, vis)
     
  
    # vertically down
    if (mat[n + 1][m] == 0):
        if (vis[n + 1][m]==False):
            ans4 = 1 + findMinSteps(mat, n + 1, m, dp, vis)
     
  
    # minimum of every path
    dp[n][m] = min(ans1, min(ans2, min(ans3, ans4)))
    return dp[n][m]
 
  
# Function that returns the minimum steps
def minimumSteps(mat, n, m):
 
    # index to store the location at
    # which you are standing
    twox = -1
    twoy = -1
  
    # find '2' in the matrix
    for i in range(n):
        for j in range(m):
            if (mat[i][j] == 2):
                twox = i
                twoy = j
                break
             
         
        if (twox != -1):
            break
     
  
    # Initialize dp matrix with -1
    dp=[[-1 for i in range(col)] for i in range(r)]
     
  
    # Initialize vis matrix with false
    vis=[[False for i in range(col)] for i in range(r)]
     
  
    # Call function to find out minimum steps
    # using memoization and recursion
    res = findMinSteps(mat, twox, twoy, dp, vis)
  
    # if not possible
    if (res >= 10**9):
        return -1
    else:
        return res
 
  
# Driver Code
 
 
mat= [ [ 1, 1, 1, 0, 1 ],
      [ 1, 0, 2, 0, 1 ],
      [ 0, 0, 1, 0, 1 ],
      [ 1, 0, 1, 1, 0 ] ]
 
print(minimumSteps(mat, r, col))
 
#this is contributed by Mohit kumar 29


C#




// C# program to find Minimum steps
// to reach any of the boundary
// edges of a matrix
 
using System;
 
class Solution
{
static int r=4,c=5;
 
    // Function to find out minimum steps
    static int findMinSteps(int [,]mat, int n, int m, int [,]dp, bool [,]vis)
    {
        // boundary edges reached
        if (n == 0 || m == 0 || n == (r - 1) || m == (c - 1)) {
            return 0;
        }
     
        // already had a route through this
        // point, hence no need to re-visit
        if (dp[n,m] != -1)
            return dp[n,m];
     
        // visiting a position
        vis[n,m] = true;
     
        int ans1, ans2, ans3, ans4;
     
        ans1 = ans2 = ans3 = ans4 = (int)1e9;
     
        // vertically up
        if (mat[n - 1,m] == 0) {
            if (!vis[n - 1,m])
                ans1 = 1 + findMinSteps(mat, n - 1, m, dp, vis);
        }
     
        // horizontally right
        if (mat[n,m + 1] == 0) {
            if (!vis[n,m + 1])
                ans2 = 1 + findMinSteps(mat, n, m + 1, dp, vis);
        }
     
        // horizontally left
        if (mat[n,m - 1] == 0) {
            if (!vis[n,m - 1])
                ans3 = 1 + findMinSteps(mat, n, m - 1, dp, vis);
        }
     
        // vertically down
        if (mat[n + 1,m] == 0) {
            if (!vis[n + 1,m])
                ans4 = 1 + findMinSteps(mat, n + 1, m, dp, vis);
        }
     
        // minimum of every path
        dp[n,m] = Math.Min(ans1, Math.Min(ans2, Math.Min(ans3, ans4)));
        return dp[n,m];
    }
     
    // Function that returns the minimum steps
    static int minimumSteps(int [,]mat, int n, int m)
    {
        // index to store the location at
        // which you are standing
        int twox = -1;
        int twoy = -1;
     
        // find '2' in the matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (mat[i,j] == 2) {
                    twox = i;
                    twoy = j;
                    break;
                }
            }
            if (twox != -1)
                break;
        }
     
        // Initialize dp matrix with -1
        int [,]dp = new int[r,r];
        for(int j=0;j<r;j++)
            for(int i=0;i<r;i++)
                dp[j,i]=-1;
     
        // Initialize vis matrix with false
        bool [,]vis= new bool [r,r];
        for(int j=0;j<r;j++)
            for(int i=0;i<r;i++)
                vis[j,i]=false;
     
        // Call function to find out minimum steps
        // using memoization and recursion
        int res = findMinSteps(mat, twox, twoy, dp, vis);
     
        // if not possible
        if (res >= 1e9)
            return -1;
        else
            return res;
    }
     
    // Driver Code
    public static void Main()
    {
        int [,]mat = { { 1, 1, 1, 0, 1 },
                        { 1, 0, 2, 0, 1 },
                        { 0, 0, 1, 0, 1 },
                        { 1, 0, 1, 1, 0 }, };
     
        Console.WriteLine(minimumSteps(mat, r, c));
    }
    // This code is contributed by Ryuga
 
}


Javascript




<script>
    // Javascript program to find Minimum steps
    // to reach any of the boundary
    // edges of a matrix
     
    let  r=4,c=5;
   
    // Function to find out minimum steps
    function findMinSteps(mat, n, m, dp, vis)
    {
        // boundary edges reached
        if (n == 0 || m == 0 || n == (r - 1) || m == (c - 1)) {
            return 0;
        }
 
        // already had a route through this
        // point, hence no need to re-visit
        if (dp[n][m] != -1)
            return dp[n][m];
 
        // visiting a position
        vis[n][m] = true;
 
        let ans1, ans2, ans3, ans4;
 
        ans1 = ans2 = ans3 = ans4 = 1e9;
 
        // vertically up
        if (mat[n - 1][m] == 0) {
            if (!vis[n - 1][m])
                ans1 = 1 + findMinSteps(mat, n - 1, m, dp, vis);
        }
 
        // horizontally right
        if (mat[n][m + 1] == 0) {
            if (!vis[n][m + 1])
                ans2 = 1 + findMinSteps(mat, n, m + 1, dp, vis);
        }
 
        // horizontally left
        if (mat[n][m - 1] == 0) {
            if (!vis[n][m - 1])
                ans3 = 1 + findMinSteps(mat, n, m - 1, dp, vis);
        }
 
        // vertically down
        if (mat[n + 1][m] == 0) {
            if (!vis[n + 1][m])
                ans4 = 1 + findMinSteps(mat, n + 1, m, dp, vis);
        }
 
        // minimum of every path
        dp[n][m] = Math.min(ans1, Math.min(ans2, Math.min(ans3, ans4)));
        return dp[n][m];
    }
 
    // Function that returns the minimum steps
    function minimumSteps(mat, n, m)
    {
        // index to store the location at
        // which you are standing
        let twox = -1;
        let twoy = -1;
 
        // find '2' in the matrix
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < m; j++) {
                if (mat[i][j] == 2) {
                    twox = i;
                    twoy = j;
                    break;
                }
            }
            if (twox != -1)
                break;
        }
 
        // Initialize dp matrix with -1
        let dp = new Array(r);
        for(let j=0;j<r;j++)
        {
            dp[j] = new Array(r);
            for(let i=0;i<r;i++)
            {
                dp[j][i]=-1;
            }
        }
 
        // Initialize vis matrix with false
        let vis = new Array(r);
        for(let j=0;j<r;j++)
        {
            vis[j] = new Array(r);
            for(let i=0;i<r;i++)
            {
                vis[j][i]=false;
            }
        }
 
        // Call function to find out minimum steps
        // using memoization and recursion
        let res = findMinSteps(mat, twox, twoy, dp, vis);
 
        // if not possible
        if (res >= 1e9)
            return -1;
        else
            return res;
    }
     
    let mat = [ [ 1, 1, 1, 0, 1 ],
               [ 1, 0, 2, 0, 1 ],
               [ 0, 0, 1, 0, 1 ],
               [ 1, 0, 1, 1, 0 ] ];
    
    document.write( minimumSteps(mat, r, c));
 
// This code is contributed by suresh07.
</script>


Output

2

Complexity Analysis:

  • Time Complexity: O(N^2), as we are using a for loop to traverse N times and in each traversal, we are calling the function findMinSteps which costs O(N) time, so the effective time will be O(N*N).
  • Auxiliary Space: O(N^2), as we are using extra space for the dp matrix.

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads