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 the above, BFS can be used 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++
#include <bits/stdc++.h>
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;
}
|
Java
import java.util.*;
class GFG
{
static int minSteps( int arr[], int n)
{
boolean [] v = new boolean [n];
Queue<Integer> q = new LinkedList<>();
q.add( 0 );
int depth = 0 ;
while (q.size() > 0 )
{
int x = q.size();
while (x-- > 0 )
{
int i = q.peek();
q.poll();
if (v[i])
continue ;
if (i == n - 1 )
return depth;
v[i] = true ;
if (i + arr[i] < n)
q.add(i + arr[i]);
if (i - arr[i] >= 0 )
q.add(i - arr[i]);
}
depth++;
}
return - 1 ;
}
public static void main(String[] args)
{
int arr[] = { 1 , 1 , 1 , 1 , 1 , 1 };
int n = arr.length;
System.out.println(minSteps(arr, n));
}
}
|
Python3
def minSteps(arr,n):
v = [ 0 for i in range (n)]
q = []
q.append( 0 )
depth = 0
while ( len (q) ! = 0 ):
x = len (q)
while (x > = 1 ):
i = q[ 0 ]
q.remove(i)
x - = 1
if (v[i]):
continue ;
if (i = = n - 1 ):
return depth
v[i] = 1
if (i + arr[i] < n):
q.append(i + arr[i])
if (i - arr[i] > = 0 ):
q.append(i - arr[i])
depth + = 1
return - 1
if __name__ = = '__main__' :
arr = [ 1 , 1 , 1 , 1 , 1 , 1 ]
n = len (arr)
print (minSteps(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int minSteps( int []arr, int n)
{
Boolean[] v = new Boolean[n];
Queue< int > q = new Queue< int >();
q.Enqueue(0);
int depth = 0;
while (q.Count > 0)
{
int x = q.Count;
while (x-- > 0)
{
int i = q.Peek();
q.Dequeue();
if (v[i])
continue ;
if (i == n - 1)
return depth;
v[i] = true ;
if (i + arr[i] < n)
q.Enqueue(i + arr[i]);
if (i - arr[i] >= 0)
q.Enqueue(i - arr[i]);
}
depth++;
}
return -1;
}
public static void Main(String[] args)
{
int []arr = { 1, 1, 1, 1, 1, 1 };
int n = arr.Length;
Console.WriteLine(minSteps(arr, n));
}
}
|
Javascript
<script>
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));
</script>
|
Time complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
30 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...