Minimum steps required to reach the end of a matrix | Set 2 | Javascript 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
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 ) ) ;