Given an array arr[], where each element represents the maximum number of steps that can be made forward from that element, the task is to print all possible paths that require the minimum number of jumps to reach the end of the given array starting from the first array element.
Note: If an element is 0, then there are no moves allowed from that element.
Examples:
Input: arr[] = {1, 1, 1, 1, 1}
Output:
0 ? 1 ? 2 ? 3 ?4
Explanation:
In every step, only one jump is allowed.
Therefore, only one possible path exists to reach end of the array.Input: arr[] = {3, 3, 0, 2, 1, 2, 4, 2, 0, 0}
Output:
0 ? 3 ? 5 ? 6 ? 9
0 ? 3 ? 5 ? 7 ? 9
Approach: The idea is to use Dynamic Programming to solve this problem. Follow the steps below to solve the problem:
- Initialize an array dp[] of size N, where dp[i] stores the minimum number of jumps required to reach the end of the array arr[N – 1] from the index i
- Compute the minimum number of steps required for each index to reach the end of the array by iterating over indices N – 2 to 1. For each index, try out all possible steps that can be taken from that index, i.e. [1, arr[i]].
- While trying out all the possible steps by iterating over [1, arr[i]], for each index, update and store the minimum value of dp[i + j].
- Initialize a queue of Pair class instance, which stores the index of the current position and the path that has been traveled so far to reach that index.
- Keep updating the minimum number of steps required and finally, print the paths corresponding to those required count of steps.
Below is the implementation of the above approach:
C++
// C++ program to implement the// above approach#include <bits/stdc++.h>using namespace std;Â
// Pair Structstruct Pair{         // Stores the current index    int idx;Â
    // Stores the path    // travelled so far    string psf;Â
    // Stores the minimum jumps    // required to reach the    // last index from current index    int jmps;};Â
// Minimum jumps required to reach// end of the arrayvoid minJumps(int arr[], int dp[], int n){Â Â Â Â for(int i = 0; i < n; i++)Â Â Â Â Â Â Â Â dp[i] = INT_MAX;Â
    dp[n - 1] = 0;Â
    for(int i = n - 2; i >= 0; i--)    {                 // Stores the maximum number        // of steps that can be taken        // from the current index        int steps = arr[i];        int min = INT_MAX;Â
        for(int j = 1;                 j <= steps && i + j < n;                j++)         {                         // Checking if index stays            // within bounds            if (dp[i + j] != INT_MAX &&                 dp[i + j] < min)             {                                 // Stores the minimum                // number of jumps                // required to jump                // from (i + j)-th index                min = dp[i + j];            }        }                 if (min != INT_MAX)            dp[i] = min + 1;    }}Â
// Function to find all possible// paths to reach end of array// requiring minimum number of stepsvoid possiblePath(int arr[], int dp[], int n){Â Â Â Â queue<Pair> Queue;Â Â Â Â Pair p1 = { 0, "0", dp[0] };Â Â Â Â Queue.push(p1);Â
    while (Queue.size() > 0)    {        Pair tmp = Queue.front();        Queue.pop();Â
        if (tmp.jmps == 0)        {            cout << tmp.psf << "\n";            continue;        }Â
        for(int step = 1;                 step <= arr[tmp.idx];                 step++)        {            if (tmp.idx + step < n &&                 tmp.jmps - 1 == dp[tmp.idx + step])            {                                 // Storing the neighbours                // of current index element                string s1 = tmp.psf + " -> " +                  to_string((tmp.idx + step));                                  Pair p2 = { tmp.idx + step, s1,                            tmp.jmps - 1 };                                           Queue.push(p2);            }        }    }}Â
// Function to find the minimum steps// and corresponding paths to reach// end of an arrayvoid Solution(int arr[], int dp[], int size){         // dp[] array stores the minimum jumps    // from each position to last position    minJumps(arr, dp, size);Â
    possiblePath(arr, dp, size);}Â
// Driver Codeint main(){    int arr[] = { 3, 3, 0, 2, 1,                  2, 4, 2, 0, 0 };Â
    int size = sizeof(arr) / sizeof(arr[0]);    int dp[size];Â
    Solution(arr, dp, size);}Â
// This code is contributed by akhilsaini |
Java
// Java Program to implement the// above approachÂ
import java.util.*;class GFG {Â
    // Pair Class instance    public static class Pair {        // Stores the current index        int idx;Â
        // Stores the path        // travelled so far        String psf;Â
        // Stores the minimum jumps        // required to reach the        // last index from current index        int jmps;Â
        // Constructor        Pair(int idx, String psf, int jmps)        {            this.idx = idx;            this.psf = psf;            this.jmps = jmps;        }    }Â
    // Minimum jumps required to reach    // end of the array    public static int[] minJumps(int[] arr)    {        int dp[] = new int[arr.length];Â
        Arrays.fill(dp, Integer.MAX_VALUE);Â
        int n = dp.length;Â
        dp[n - 1] = 0;Â
        for (int i = n - 2; i >= 0; i--) {            // Stores the maximum number            // of steps that can be taken            // from the current index            int steps = arr[i];            int min = Integer.MAX_VALUE;Â
            for (int j = 1; j <= steps && i + j < n; j++) {                // Checking if index stays                // within bounds                if (dp[i + j] != Integer.MAX_VALUE                    && dp[i + j] < min) {                    // Stores the minimum                    // number of jumps                    // required to jump                    // from (i + j)-th index                    min = dp[i + j];                }            }Â
            if (min != Integer.MAX_VALUE)                dp[i] = min + 1;        }        return dp;    }Â
    // Function to find all possible    // paths to reach end of array    // requiring minimum number of steps    public static void possiblePath(        int[] arr, int[] dp)    {Â
        Queue<Pair> queue = new LinkedList<>();        queue.add(new Pair(0, "" + 0, dp[0]));Â
        while (queue.size() > 0) {            Pair tmp = queue.remove();Â
            if (tmp.jmps == 0) {                System.out.println(tmp.psf);                continue;            }Â
            for (int step = 1;                 step <= arr[tmp.idx];                 step++) {Â
                if (tmp.idx + step < arr.length                    && tmp.jmps - 1 == dp[tmp.idx + step]) {                    // Storing the neighbours                    // of current index element                    queue.add(new Pair(                        tmp.idx + step,                        tmp.psf + " -> " + (tmp.idx + step),                        tmp.jmps - 1));                }            }        }    }Â
    // Function to find the minimum steps    // and corresponding paths to reach    // end of an array    public static void Solution(int arr[])    {        // Stores the minimum jumps from        // each position to last position        int dp[] = minJumps(arr);Â
        possiblePath(arr, dp);    }Â
    // Driver Code    public static void main(String[] args)    {        int[] arr = { 3, 3, 0, 2, 1,                      2, 4, 2, 0, 0 };        int size = arr.length;        Solution(arr);    }} |
Python3
# Python3 program to implement the# above approachfrom queue import Queueimport sysÂ
# Pair Class instanceclass Pair(object):         # Stores the current index    idx = 0Â
    # Stores the path    # travelled so far    psf = ""Â
    # Stores the minimum jumps    # required to reach the    # last index from current index    jmps = 0Â
    # Constructor    def __init__(self, idx, psf, jmps):                 self.idx = idx        self.psf = psf        self.jmps = jmpsÂ
# Minimum jumps required to reach# end of the arraydef minJumps(arr):Â
    MAX_VALUE = sys.maxsize    dp = [MAX_VALUE for i in range(len(arr))]Â
    n = len(dp)Â
    dp[n - 1] = 0Â
    for i in range(n - 2, -1, -1):                 # Stores the maximum number        # of steps that can be taken        # from the current index        steps = arr[i]        minimum = MAX_VALUEÂ
        for j in range(1, steps + 1, 1):            if i + j >= n:                break                         # Checking if index stays            # within bounds            if ((dp[i + j] != MAX_VALUE) and                (dp[i + j] < minimum)):                                     # Stores the minimum                # number of jumps                # required to jump                # from (i + j)-th index                minimum = dp[i + j]Â
        if minimum != MAX_VALUE:            dp[i] = minimum + 1                 return dpÂ
# Function to find all possible# paths to reach end of array# requiring minimum number of stepsdef possiblePath(arr, dp):Â
    queue = Queue(maxsize = 0)    p1 = Pair(0, "0", dp[0])    queue.put(p1)Â
    while queue.qsize() > 0:        tmp = queue.get()Â
        if tmp.jmps == 0:            print(tmp.psf)            continueÂ
        for step in range(1, arr[tmp.idx] + 1, 1):            if ((tmp.idx + step < len(arr)) and               (tmp.jmps - 1 == dp[tmp.idx + step])):                               # Storing the neighbours                # of current index element                p2 = Pair(tmp.idx + step, tmp.psf +                           " -> " + str((tmp.idx + step)),                         tmp.jmps - 1)                                          queue.put(p2)Â
# Function to find the minimum steps# and corresponding paths to reach# end of an arraydef Solution(arr):         # Stores the minimum jumps from    # each position to last position    dp = minJumps(arr)         possiblePath(arr, dp)Â
# Driver Codeif __name__ == "__main__":Â Â Â Â Â Â Â Â Â arr = [ 3, 3, 0, 2, 1, Â Â Â Â Â Â Â Â Â Â Â Â 2, 4, 2, 0, 0 ]Â Â Â Â size = len(arr)Â
    Solution(arr)Â
# This code is contributed by akhilsaini |
C#
// C# program to implement the// above approachusing System;using System.Collections;Â
// Pair Structpublic struct Pair{         // Stores the current index    public int idx;Â
    // Stores the path    // travelled so far    public string psf;Â
    // Stores the minimum jumps    // required to reach the    // last index from current index    public int jmps;Â
    // Constructor    public Pair(int idx, String psf, int jmps)    {        this.idx = idx;        this.psf = psf;        this.jmps = jmps;    }}Â
class GFG{Â
// Minimum jumps required to reach// end of the arraypublic static int[] minJumps(int[] arr){Â Â Â Â int[] dp = new int[arr.Length];Â Â Â Â int n = dp.Length;Â
    for(int i = 0; i < n; i++)        dp[i] = int.MaxValue;Â
    dp[n - 1] = 0;Â
    for(int i = n - 2; i >= 0; i--)    {                 // Stores the maximum number        // of steps that can be taken        // from the current index        int steps = arr[i];        int min = int.MaxValue;Â
        for(int j = 1;                 j <= steps && i + j < n;                j++)        {                         // Checking if index stays            // within bounds            if (dp[i + j] != int.MaxValue &&                 dp[i + j] < min)            {                                 // Stores the minimum                // number of jumps                // required to jump                // from (i + j)-th index                min = dp[i + j];            }        }Â
        if (min != int.MaxValue)            dp[i] = min + 1;    }    return dp;}Â
// Function to find all possible// paths to reach end of array// requiring minimum number of stepspublic static void possiblePath(int[] arr,                                int[] dp){    Queue queue = new Queue();    queue.Enqueue(new Pair(0, "0", dp[0]));Â
    while (queue.Count > 0)    {        Pair tmp = (Pair)queue.Dequeue();Â
        if (tmp.jmps == 0)         {            Console.WriteLine(tmp.psf);            continue;        }Â
        for(int step = 1;                 step <= arr[tmp.idx];                step++)         {            if (tmp.idx + step < arr.Length &&                tmp.jmps - 1 == dp[tmp.idx + step])             {                                 // Storing the neighbours                // of current index elementÂ
                queue.Enqueue(new Pair(                    tmp.idx + step,                    tmp.psf + " -> " +                    (tmp.idx + step),                   tmp.jmps - 1));            }        }    }}Â
// Function to find the minimum steps// and corresponding paths to reach// end of an arraypublic static void Solution(int[] arr){         // Stores the minimum jumps from    // each position to last position    int[] dp = minJumps(arr);Â
    possiblePath(arr, dp);}Â
// Driver Codestatic public void Main(){    int[] arr = { 3, 3, 0, 2, 1,                  2, 4, 2, 0, 0 };    int size = arr.Length;         Solution(arr);}}Â
// This code is contributed by akhilsaini |
Javascript
//JS code for the above approachclass Pair{Â
    // Stores the current index    idx;Â
    // Stores the path    // travelled so far    psf;Â
    // Stores the minimum jumps    // required to reach the    // last index from current index    jmps;Â
    // Constructor    constructor(idx, psf, jmps) {        this.idx = idx;        this.psf = psf;        this.jmps = jmps;    }}Â
// Minimum jumps required to reach// end of the arrayfunction minJumps(arr) {Â Â Â Â const MAX_VALUE = Number.MAX_SAFE_INTEGER;Â Â Â Â const dp = Array(arr.length).fill(MAX_VALUE);Â
    const n = dp.length;Â
    dp[n - 1] = 0;Â
    for (let i = n - 2; i >= 0; i--)    {             // Stores the maximum number        // of steps that can be taken        // from the current index        const steps = arr[i];        let minimum = MAX_VALUE;Â
        for (let j = 1; j <= steps; j++) {            if (i + j >= n) break;Â
            // Checking if index stays            // within bounds            if (dp[i + j] !== MAX_VALUE && dp[i + j] < minimum)            {                             // Stores the minimum                // number of jumps                // required to jump                // from (i + j)-th index                minimum = dp[i + j];            }        }Â
        if (minimum !== MAX_VALUE) dp[i] = minimum + 1;    }    return dp;}Â
// Function to find all possible// paths to reach end of array// requiring minimum numberfunction possiblePath(arr, dp) {const queue = [];queue.push(new Pair(0, "0", dp[0]));Â
while (queue.length > 0) {Â Â Â Â const tmp = queue.shift();Â
    if (tmp.jmps === 0) {        document.write(tmp.psf +"<br>");        continue;    }Â
    for (let step = 1; step <= arr[tmp.idx]; step++)    {        if (tmp.idx + step < arr.length && tmp.jmps - 1 === dp[tmp.idx + step])        {                     // Storing the neighbours            // of current index element            queue.push(new Pair(tmp.idx + step, tmp.psf + " -> " + (tmp.idx + step), tmp.jmps - 1));        }    }}}Â
// Function to find the minimum steps// and corresponding paths to reach// end of an arrayfunction Solution(arr){Â
// Stores the minimum jumps from// each position to last positionconst dp = minJumps(arr);Â
possiblePath(arr, dp);}Â
// Driver Codeconst arr = [3, 3, 0, 2, 1, 2, 4, 2, 0, 0];const size = arr.length;Solution(arr);Â
// This code is contributed by lokeshpotta20. |
0 -> 3 -> 5 -> 6 -> 9 0 -> 3 -> 5 -> 7 -> 9
Â
Time Complexity: O(N2)
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
