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
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:
- This problem can be visualized as a directed graph where ith cell is connected with cells i + arr[i] and i – arr[i].
- And the graph is un-weighted.
Due to above, BFS can be used to to find the shortest path between 0th and the (N – 1)th index. We will use the following algorithm:
- Push index 0 in a queue.
- Push all the adjacent cells to 0 in the queue.
- Repeat the above steps i.e. traverse all the elements in the queue individually again if they have not been visited/traversed before.
- Repeat till we don’t reach the index N – 1.
- 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++
// C++ implementation of the approach #include <bits/stdc++.h> 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
// 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<Integer> 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 */ |
Python3
# 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 |
C#
// 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 |
5
Time complexity: O(N)
Recommended Posts:
- Minimize the number of steps required to reach the end of the array
- Number of steps required to reach point (x,y) from (0,0) using zig-zag way
- Minimum steps required to reach the end of a matrix | Set 2
- Minimum steps to reach end of array under constraints
- Find the minimum number of steps to reach M from N
- Minimum steps to reach end from start by performing multiplication and mod operations with array elements
- Minimum steps required to reduce all the elements of the array to zero
- Minimum number of moves required to reach the destination by the king in a chess board
- Minimum steps to reach a destination
- Minimum steps to reach target by a Knight | Set 1
- Minimum steps to reach any of the boundary edges of a matrix | Set-2
- Check if the given number K is enough to reach the end of an array
- Find the minimum number of moves to reach end of the array
- Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps
- Minimum number of changes required to make the given array an AP
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.



