Minimum steps required to reach the end of a matrix | Set 2
Last Updated :
21 Dec, 2022
Given a 2d-matrix mat[][] consisting of positive integers, the task is to find the minimum number of steps required to reach the end of the matrix. If we are at cell (i, j) we can go to cells (i, j + arr[i][j]) or (i + arr[i][j], j). We cannot go out of bounds. If no path exists then print -1.
Examples:
Input: mat[][] = {
{2, 1, 2},
{1, 1, 1},
{1, 1, 1}}
Output: 2
The path will be {0, 0} -> {0, 2} -> {2, 2}
Thus, we are reaching there in two steps.
Input: mat[][] = {
{1, 1, 1},
{1, 1, 1},
{1, 1, 1}}
Output: 4
Approach: We have already discussed a dynamic programming based approach for this problem in this article. This problem can also be solved using breadth first search (BFS).
The algorithm is as follows:
- Push (0, 0) in a queue.
- Traverse (0, 0) i.e. push all the cells it can visit in the queue.
- Repeat the above steps, i.e. traverse all the elements in the queue individually again if they have not been visited/traversed before.
- Repeat till we don’t reach the cell (N-1, N-1).
- The depth of this traversal will give the minimum steps required to reach the end.
Remember to mark a cell visited after it has been traversed. For this, we will use a 2D boolean array.
Why BFS works?
- This whole scenario can be considered equivalent to a directed graph where each cell is connected to at most two more cells({i, j+arr[i][j]} and {i+arr[i][j], j}).
- The graph is unweighted. BFS can find the shortest path in such scenarios.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define n 3
using namespace std;
int minSteps( int arr[][n])
{
bool v[n][n] = { 0 };
queue<pair< int , int > > q;
q.push({ 0, 0 });
int depth = 0;
while (q.size() != 0) {
int x = q.size();
while (x--) {
pair< int , int > y = q.front();
int i = y.first, j = y.second;
q.pop();
if (v[i][j])
continue ;
if (i == n - 1 && j == n - 1)
return depth;
v[i][j] = 1;
if (i + arr[i][j] < n)
q.push({ i + arr[i][j], j });
if (j + arr[i][j] < n)
q.push({ i, j + arr[i][j] });
}
depth++;
}
return -1;
}
int main()
{
int arr[n][n] = { { 1, 1, 1 },
{ 1, 1, 1 },
{ 1, 1, 1 } };
cout << minSteps(arr);
return 0;
}
|
Java
import java.util.*;
import java.io.*;
public class GFG
{
static int n= 3 ;
static class Pair
{
int first , second;
Pair( int a, int b)
{
first = a;
second = b;
}
}
static int minSteps( int arr[][])
{
boolean v[][] = new boolean [n][n];
Queue<Pair> q = new LinkedList<Pair>();
q.add( new Pair( 0 , 0 ));
int depth = 0 ;
while (q.size() != 0 )
{
int x = q.size();
while (x--> 0 )
{
Pair y = q.peek();
int i = y.first, j = y.second;
q.remove();
if (v[i][j])
continue ;
if (i == n - 1 && j == n - 1 )
return depth;
v[i][j] = true ;
if (i + arr[i][j] < n)
q.add( new Pair( i + arr[i][j], j ));
if (j + arr[i][j] < n)
q.add( new Pair( i, j + arr[i][j] ));
}
depth++;
}
return - 1 ;
}
public static void main(String args[])
{
int arr[][] = { { 1 , 1 , 1 },
{ 1 , 1 , 1 },
{ 1 , 1 , 1 } };
System.out.println(minSteps(arr));
}
}
|
Python3
n = 3
def minSteps(arr):
v = [[ 0 for i in range (n)] for j in range (n)]
q = [[ 0 , 0 ]]
depth = 0
while ( len (q) ! = 0 ):
x = len (q)
while (x > 0 ):
y = q[ 0 ]
i = y[ 0 ]
j = y[ 1 ]
q.remove(q[ 0 ])
x - = 1
if (v[i][j]):
continue
if (i = = n - 1 and j = = n - 1 ):
return depth
v[i][j] = 1
if (i + arr[i][j] < n):
q.append([i + arr[i][j], j])
if (j + arr[i][j] < n):
q.append([i, j + arr[i][j]])
depth + = 1
return - 1
if __name__ = = '__main__' :
arr = [[ 1 , 1 , 1 ],
[ 1 , 1 , 1 ],
[ 1 , 1 , 1 ]]
print (minSteps(arr))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int n= 3 ;
public class Pair
{
public int first , second;
public Pair( int a, int b)
{
first = a;
second = b;
}
}
static int minSteps( int [,]arr)
{
Boolean [,]v = new Boolean[n,n];
Queue<Pair> q = new Queue<Pair>();
q.Enqueue( new Pair( 0, 0 ));
int depth = 0;
while (q.Count != 0)
{
int x = q.Count;
while (x-->0)
{
Pair y = q.Peek();
int i = y.first, j = y.second;
q.Dequeue();
if (v[i,j])
continue ;
if (i == n - 1 && j == n - 1)
return depth;
v[i,j] = true ;
if (i + arr[i,j] < n)
q.Enqueue( new Pair( i + arr[i,j], j ));
if (j + arr[i,j] < n)
q.Enqueue( new Pair( i, j + arr[i,j] ));
}
depth++;
}
return -1;
}
public static void Main()
{
int [,]arr = { { 1, 1, 1 },
{ 1, 1, 1 },
{ 1, 1, 1 } };
Console.WriteLine(minSteps(arr));
}
}
|
Javascript
<script>
var n = 3;
function minSteps(arr)
{
var v = Array.from(Array(n), ()=> Array(n).fill(0));
var q = [];
q.push([0, 0 ]);
var depth = 0;
while (q.length != 0) {
var x = q.length;
while (x--) {
var y = q[0];
var i = y[0], j = y[1];
q.shift();
if (v[i][j])
continue ;
if (i == n - 1 && j == n - 1)
return depth;
v[i][j] = 1;
if (i + arr[i][j] < n)
q.push([ i + arr[i][j], j ]);
if (j + arr[i][j] < n)
q.push([i, j + arr[i][j] ]);
}
depth++;
}
return -1;
}
var arr = [ [ 1, 1, 1 ],
[ 1, 1, 1 ],
[ 1, 1, 1 ] ];
document.write( minSteps(arr));
</script>
|
Time Complexity: O(n2)
Auxiliary Space: O(n2)
Share your thoughts in the comments
Please Login to comment...