Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmMinimize the number of steps required to reach the end of the...

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:
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:  

  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 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:  

  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++




// 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


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the minimum steps
// required to reach the end
// of the given array
function minSteps(arr, n)
{
    // Array to determine whether
    // a cell has been visited before
    var v = Array(n).fill(0);
 
    // Queue for bfs
    var q = [];
 
    // Push the source i.e. index 0
    q.push(0);
 
    // Variable to store
    // the depth of search
    var depth = 0;
 
    // BFS algorithm
    while (q.length != 0) {
 
        // Current queue size
        var x = q.length;
        while (x--) {
 
            // Top-most element of queue
            var i = q[0];
            q.shift();
 
            // 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
var arr = [1, 1, 1, 1, 1, 1];
var n = arr.length;
document.write( minSteps(arr, n));
 
 
</script>


Output: 

5

 

Time complexity: O(N)

Auxiliary Space: O(N)
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments