# Minimize the number of steps required to reach the end of the array | Set 2

Given an integer array arr[] of length N consisting of positive integers, the task is to minimize the number of steps required to reach the arr[N – 1] starting from arr[0]. At a given step if we are at index i we can go to index i – arr[i] or i + arr[i] given we have not visited those indexes before. Also, we cannot go outside the bounds of the array. Print -1 if there is no possible way.

Examples:

Input: arr[] = {1, 1, 1}
Output: 2
The path will be 0 -> 1 -> 2.

Input: arr[] = {2, 1}
Output: -1

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: We have already discussed a dynamic programming based approach in this article which has a time complexity of O(n * 2n).
Here we’re going to discuss a BFS based solution:

1. This problem can be visualized as a directed graph where ith cell is connected with cells i + arr[i] and i – arr[i].
2. And the graph is un-weighted.

Due to above, BFS can be used to find the shortest path between 0th and the (N – 1)th index. We will use the following algorithm:

1. Push index 0 in a queue.
2. Push all the adjacent cells to 0 in the queue.
3. Repeat the above steps i.e. traverse all the elements in the queue individually again if they have not been visited/traversed before.
4. Repeat till we don’t reach the index N – 1.
5. 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 boolean array.

Below is the implementation of the above approach:

 `// C++ implementation of the approach ` `#include ` `using` `namespace` `std; ` ` `  `// Function to return the minimum steps ` `// required to reach the end ` `// of the given array ` `int` `minSteps(``int` `arr[], ``int` `n) ` `{ ` `    ``// Array to determine whether ` `    ``// a cell has been visited before ` `    ``bool` `v[n] = { 0 }; ` ` `  `    ``// Queue for bfs ` `    ``queue<``int``> q; ` ` `  `    ``// Push the source i.e. index 0 ` `    ``q.push(0); ` ` `  `    ``// Variable 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 ` `            ``int` `i = q.front(); ` `            ``q.pop(); ` ` `  `            ``// Base case ` `            ``if` `(v[i]) ` `                ``continue``; ` ` `  `            ``// If we reach the destination ` `            ``// i.e. index (n - 1) ` `            ``if` `(i == n - 1) ` `                ``return` `depth; ` ` `  `            ``// Marking the cell visited ` `            ``v[i] = 1; ` ` `  `            ``// Pushing the adjacent nodes ` `            ``// i.e. indices reachable ` `            ``// from the current index ` `            ``if` `(i + arr[i] < n) ` `                ``q.push(i + arr[i]); ` `            ``if` `(i - arr[i] >= 0) ` `                ``q.push(i - arr[i]); ` `        ``} ` `        ``depth++; ` `    ``} ` ` `  `    ``return` `-1; ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``int` `arr[] = { 1, 1, 1, 1, 1, 1 }; ` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(``int``); ` ` `  `    ``cout << minSteps(arr, n); ` ` `  `    ``return` `0; ` `} `

 `// Java implementation of the approach  ` `import` `java.util.*; ` ` `  `class` `GFG  ` `{ ` ` `  `// Function to return the minimum steps ` `// required to reach the end ` `// of the given array ` `static` `int` `minSteps(``int` `arr[], ``int` `n) ` `{ ` `    ``// Array to determine whether ` `    ``// a cell has been visited before ` `    ``boolean``[] v = ``new` `boolean``[n]; ` ` `  `    ``// Queue for bfs ` `    ``Queue q = ``new` `LinkedList<>(); ` ` `  `    ``// Push the source i.e. index 0 ` `    ``q.add(``0``); ` ` `  `    ``// Variable 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 ` `            ``int` `i = q.peek(); ` `            ``q.poll(); ` ` `  `            ``// Base case ` `            ``if` `(v[i]) ` `                ``continue``; ` ` `  `            ``// If we reach the destination ` `            ``// i.e. index (n - 1) ` `            ``if` `(i == n - ``1``) ` `                ``return` `depth; ` ` `  `            ``// Marking the cell visited ` `            ``v[i] = ``true``; ` ` `  `            ``// Pushing the adjacent nodes ` `            ``// i.e. indices reachable ` `            ``// from the current index ` `            ``if` `(i + arr[i] < n) ` `                ``q.add(i + arr[i]); ` `            ``if` `(i - arr[i] >= ``0``) ` `                ``q.add(i - arr[i]); ` `        ``} ` `        ``depth++; ` `    ``} ` ` `  `    ``return` `-``1``; ` `} ` ` `  `// Driver code ` `public` `static` `void` `main(String[] args)  ` `{ ` `    ``int` `arr[] = { ``1``, ``1``, ``1``, ``1``, ``1``, ``1` `}; ` `    ``int` `n = arr.length; ` `    ``System.out.println(minSteps(arr, n)); ` `} ` `} ` ` `  `/* This code contributed by PrinciRaj1992 */`

 `# Python 3 implementation of the approach ` ` `  `# Function to return the minimum steps ` `# required to reach the end ` `# of the given array ` `def` `minSteps(arr,n): ` `     `  `    ``# Array to determine whether ` `    ``# a cell has been visited before ` `    ``v ``=` `[``0` `for` `i ``in` `range``(n)] ` ` `  `    ``# Queue for bfs ` `    ``q ``=` `[] ` ` `  `    ``# Push the source i.e. index 0 ` `    ``q.append(``0``) ` ` `  `    ``# Variable to store ` `    ``# the depth of search ` `    ``depth ``=` `0` ` `  `    ``# BFS algorithm ` `    ``while` `(``len``(q) !``=` `0``): ` `        ``# Current queue size ` `        ``x ``=` `len``(q) ` `        ``while` `(x >``=` `1``): ` `            ``# Top-most element of queue ` `            ``i ``=` `q[``0``] ` `            ``q.remove(i) ` `             `  `            ``x ``-``=` `1` ` `  `            ``# Base case ` `            ``if` `(v[i]): ` `                ``continue``; ` ` `  `            ``# If we reach the destination ` `            ``# i.e. index (n - 1) ` `            ``if` `(i ``=``=` `n ``-` `1``): ` `                ``return` `depth ` ` `  `            ``# Marking the cell visited ` `            ``v[i] ``=` `1` ` `  `            ``# Pushing the adjacent nodes ` `            ``# i.e. indices reachable ` `            ``# from the current index ` `            ``if` `(i ``+` `arr[i] < n): ` `                ``q.append(i ``+` `arr[i]) ` `            ``if` `(i ``-` `arr[i] >``=` `0``): ` `                ``q.append(i ``-` `arr[i]) ` `                 `  `         `  `        ``depth ``+``=` `1` ` `  `    ``return` `-``1` ` `  `# Driver code ` `if` `__name__ ``=``=` `'__main__'``: ` `    ``arr ``=` `[``1``, ``1``, ``1``, ``1``, ``1``, ``1``] ` `    ``n ``=` `len``(arr) ` ` `  `    ``print``(minSteps(arr, n)) ` ` `  `# This code is contributed by ` `# Surendra_Gangwar `

 `// A C# implementation of the approach  ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG  ` `{  ` ` `  `// Function to return the minimum steps  ` `// required to reach the end  ` `// of the given array  ` `static` `int` `minSteps(``int` `[]arr, ``int` `n)  ` `{  ` `    ``// Array to determine whether  ` `    ``// a cell has been visited before  ` `    ``Boolean[] v = ``new` `Boolean[n];  ` ` `  `    ``// Queue for bfs  ` `    ``Queue<``int``> q = ``new` `Queue<``int``>();  ` ` `  `    ``// Push the source i.e. index 0  ` `    ``q.Enqueue(0);  ` ` `  `    ``// Variable 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  ` `            ``int` `i = q.Peek();  ` `            ``q.Dequeue();  ` ` `  `            ``// Base case  ` `            ``if` `(v[i])  ` `                ``continue``;  ` ` `  `            ``// If we reach the destination  ` `            ``// i.e. index (n - 1)  ` `            ``if` `(i == n - 1)  ` `                ``return` `depth;  ` ` `  `            ``// Marking the cell visited  ` `            ``v[i] = ``true``;  ` ` `  `            ``// Pushing the adjacent nodes  ` `            ``// i.e. indices reachable  ` `            ``// from the current index  ` `            ``if` `(i + arr[i] < n)  ` `                ``q.Enqueue(i + arr[i]);  ` `            ``if` `(i - arr[i] >= 0)  ` `                ``q.Enqueue(i - arr[i]);  ` `        ``}  ` `        ``depth++;  ` `    ``}  ` ` `  `    ``return` `-1;  ` `}  ` ` `  `// Driver code  ` `public` `static` `void` `Main(String[] args)  ` `{  ` `    ``int` `[]arr = { 1, 1, 1, 1, 1, 1 };  ` `    ``int` `n = arr.Length;  ` `    ``Console.WriteLine(minSteps(arr, n));  ` `}  ` `}  ` ` `  `// This code contributed by Rajput-Ji `

Output:
```5
```

Time complexity: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :