Minimize the number of steps required to reach the end of the array | Set 2 | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int arr [ ] , int n ) { bool v [ n ] = { 0 } ; queue < int > q ; q . push ( 0 ) ; int depth = 0 ; while ( q . size ( ) != 0 ) { int x = q . size ( ) ; while ( x -- ) { int i = q . front ( ) ; q . pop ( ) ; 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 ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << minSteps ( arr , n ) ; return 0 ; }