text: Minimum steps required to reach the end of a matrix | Set 2 | C ++ implementation of the approach ; Function to return the minimum steps required to reach the end of the matrix ; Array to determine whether a cell has been visited before ; Queue for bfs ; Initializing queue ; To store the depth of search ; BFS algorithm ; Current queue size ; Top - most element of queue ; To store index of cell for simplicity ; Base case ; If we reach ( n - 1 , n - 1 ) ; Marking the cell visited ; Pushing the adjacent cells in the queue that can be visited from the current cell ; Driver code
code: #include <bits/stdc++.h> NEW_LINE #define n  3 NEW_LINE 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 ; }