Minimum steps required to reach the end of a matrix | Set 2

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++
// C++ implementation of the approach#include <bits/stdc++.h>#define n 3using namespace std;Â
// Function to return the minimum steps// required to reach the end of the matrixint minSteps(int arr[][n]){    // Array to determine whether    // a cell has been visited before    bool v[n][n] = { 0 };Â
    // Queue for bfs    queue<pair<int, int> > q;Â
    // Initializing queue    q.push({ 0, 0 });Â
    // To store the depth of search    int depth = 0;Â
    // BFS algorithm    while (q.size() != 0) {Â
        // Current queue size        int x = q.size();        while (x--) {Â
            // Top-most element of queue            pair<int, int> y = q.front();Â
            // To store index of cell            // for simplicity            int i = y.first, j = y.second;            q.pop();Â
            // Base case            if (v[i][j])                continue;Â
            // If we reach (n-1, n-1)            if (i == n - 1 && j == n - 1)                return depth;Â
            // Marking the cell visited            v[i][j] = 1;Â
            // Pushing the adjacent cells in the            // queue that can be visited            // from the current cell            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;}Â
// Driver codeint main(){    int arr[n][n] = { { 1, 1, 1 },                      { 1, 1, 1 },                      { 1, 1, 1 } };Â
    cout << minSteps(arr);Â
    return 0;} |
Java
// Java implementation of the approach 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;Â Â Â Â }}Â
// Function to return the minimum steps // required to reach the end of the matrix static int minSteps(int arr[][]) {     // Array to determine whether     // a cell has been visited before     boolean v[][] = new boolean[n][n]; Â
    // Queue for bfs     Queue<Pair> q = new LinkedList<Pair>(); Â
    // Initializing queue     q.add(new Pair( 0, 0 )); Â
    // To store the depth of search     int depth = 0; Â
    // BFS algorithm     while (q.size() != 0)     { Â
        // Current queue size         int x = q.size();         while (x-->0)         { Â
            // Top-most element of queue             Pair y = q.peek(); Â
            // To store index of cell             // for simplicity             int i = y.first, j = y.second;             q.remove(); Â
            // Base case             if (v[i][j])                 continue; Â
            // If we reach (n-1, n-1)             if (i == n - 1 && j == n - 1)                 return depth; Â
            // Marking the cell visited             v[i][j] = true; Â
            // Pushing the adjacent cells in the             // queue that can be visited             // from the current cell             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; } Â
// Driver code public static void main(String args[]){ Â Â Â Â int arr[][] = { { 1, 1, 1 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 1, 1, 1 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 1, 1, 1 } }; Â
    System.out.println(minSteps(arr)); }}Â
// This code is contributed by Arnab Kundu |
Python3
# Python 3 implementation of the approachn = 3Â
# Function to return the minimum steps# required to reach the end of the matrixdef minSteps(arr):         # Array to determine whether    # a cell has been visited before    v = [[0 for i in range(n)] for j in range(n)]Â
    # Queue for bfs    q = [[0,0]]Â
    # To store the depth of search    depth = 0Â
    # BFS algorithm    while (len(q) != 0):                 # Current queue size        x = len(q)        while (x > 0):                         # Top-most element of queue            y = q[0]Â
            # To store index of cell            # for simplicity            i = y[0]            j = y[1]            q.remove(q[0])Â
            x -= 1Â
            # Base case            if (v[i][j]):                continueÂ
            # If we reach (n-1, n-1)            if (i == n - 1 and j == n - 1):                return depthÂ
            # Marking the cell visited            v[i][j] = 1Â
            # Pushing the adjacent cells in the            # queue that can be visited            # from the current cell            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Â
# Driver codeif __name__ == '__main__':    arr = [[1, 1, 1],            [1, 1, 1],            [1, 1, 1]]Â
    print(minSteps(arr))Â
# This code is contributed by# Surendra_Gangwar |
C#
// C# implementation of the approach 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;Â Â Â Â }}Â
// Function to return the minimum steps // required to reach the end of the matrix static int minSteps(int [,]arr) {     // Array to determine whether     // a cell has been visited before     Boolean [,]v = new Boolean[n,n]; Â
    // Queue for bfs     Queue<Pair> q = new Queue<Pair>(); Â
    // Initializing queue     q.Enqueue(new Pair( 0, 0 )); Â
    // To store the depth of search     int depth = 0; Â
    // BFS algorithm     while (q.Count != 0)     { Â
        // Current queue size         int x = q.Count;         while (x-->0)         { Â
            // Top-most element of queue             Pair y = q.Peek(); Â
            // To store index of cell             // for simplicity             int i = y.first, j = y.second;             q.Dequeue(); Â
            // Base case             if (v[i,j])                 continue; Â
            // If we reach (n-1, n-1)             if (i == n - 1 && j == n - 1)                 return depth; Â
            // Marking the cell visited             v[i,j] = true; Â
            // Pushing the adjacent cells in the             // queue that can be visited             // from the current cell             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; } Â
// Driver code public static void Main(){ Â Â Â Â int [,]arr = { { 1, 1, 1 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 1, 1, 1 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 1, 1, 1 } }; Â
    Console.WriteLine(minSteps(arr)); }}Â
// This code contributed by Rajput-Ji |
Javascript
<script>Â
Â
// Javascript implementation of the approachvar n =Â 3;Â
// Function to return the minimum steps// required to reach the end of the matrixfunction minSteps(arr){    // Array to determine whether    // a cell has been visited before    var v = Array.from(Array(n), ()=> Array(n).fill(0));Â
    // Queue for bfs    var q = [];Â
    // Initializing queue    q.push([0, 0 ]);Â
    // To store the depth of search    var depth = 0;Â
    // BFS algorithm    while (q.length != 0) {Â
        // Current queue size        var x = q.length;        while (x--) {Â
            // Top-most element of queue            var y = q[0];Â
            // To store index of cell            // for simplicity            var i = y[0], j = y[1];            q.shift();Â
            // Base case            if (v[i][j])                continue;Â
            // If we reach (n-1, n-1)            if (i == n - 1 && j == n - 1)                return depth;Â
            // Marking the cell visited            v[i][j] = 1;Â
            // Pushing the adjacent cells in the            // queue that can be visited            // from the current cell            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;}Â
// Driver codevar arr = [ [ 1, 1, 1 ],                  [ 1, 1, 1 ],                  [ 1, 1, 1 ] ];document.write( minSteps(arr));Â
Â
</script> |
4
Â
Time Complexity: O(n2)
Auxiliary Space: O(n2)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



