Minimize the number of steps required to reach the end of the array | Set 2 | Function to return the minimum steps required to reach the end of the given array ; Array to determine whether a cell has been visited before ; Queue for bfs ; Push the source i . e . index 0 ; Variable to store the depth of search ; BFS algorithm ; Current queue size ; Top - most element of queue ; Base case ; If we reach the destination i . e . index ( n - 1 ) ; Marking the cell visited ; Pushing the adjacent nodes i . e . indices reachable from the current index ; Driver code
function minSteps ( arr , n ) { var v = Array ( n ) . fill ( 0 ) ; var q = [ ] ; q . push ( 0 ) ; var depth = 0 ; while ( q . length != 0 ) { var x = q . length ; while ( x -- ) { var i = q [ 0 ] ; q . shift ( ) ; if ( v [ i ] ) continue ; if ( i == n - 1 ) return depth ; v [ i ] = 1 ; if ( i + arr [ i ] < n ) q . push ( i + arr [ i ] ) ; if ( i - arr [ i ] >= 0 ) q . push ( i - arr [ i ] ) ; } depth ++ ; } return - 1 ; } var arr = [ 1 , 1 , 1 , 1 , 1 , 1 ] ; var n = arr . length ; document . write ( minSteps ( arr , n ) ) ;