Frog Jump Ii

Solution For Frog Jump Ii

Problem Statement:

Given an array of stones where stones[i] represents the position of the ith stone, you need to find the minimum number of jumps required to cross the stones. You start at the 0th stone and your final destination is the (n – 1)th stone.

You are allowed to make only the following jumps:

  1. You can jump from the ith stone to the (i + k – 1)th stone. Here, k is a constant value and represents the maximum length of a jump.
  2. You can jump from the ith stone to the (i + k)th stone. Here, k is a constant value and represents the maximum length of a jump.
  3. You can jump from the ith stone to the (i + k + 1)th stone. Here, k is a constant value and represents the maximum length of a jump.

You can only jump if the destination stone is not beyond the end of the array and is not in the water.

If it’s not possible to reach the destination stone, return -1.

Solution Approach:

  1. The first step is to create a set containing all the stones that are in the array, this will ensure that we can check if we can jump to a certain stone.
  2. Then, we initialise a queue, where each element of the queue is a tuple containing the index of the stone and the number of jumps needed to reach that stone. Initially, we start with the 0th stone and 0 jumps.
  3. We then start a loop, where we pop the first element from the queue.
  4. We check if the current stone is the last stone, which is our destination. If it is, we return the number of jumps needed to reach that stone.
  5. We then generate all the possible jumps from that stone and check if the destination stone is in our set of stones.
  6. If the destination stone is in the set of stones, we add the tuple of the destination stone and the number of jumps needed to reach that stone to the queue.
  7. We repeat steps 3 to 6 until the queue is empty.
  8. If we reach the end of the loop and have not found a path to the destination stone, we return -1.

Code:

def frogJumpII(stones, k):
stones_set = set(stones)
queue = [(0, 0)] visited = set()
while queue:
current, jumps = queue.pop(0)
visited.add(current)
if current == stones[-1]:
return jumps
for i in range(1, k+2):
next_jump = current + i
if next_jump in stones_set and next_jump not in visited:
queue.append((next_jump, jumps+1))
return -1

Time Complexity: O(n * k)

Space Complexity: O(n)

Step by Step Implementation For Frog Jump Ii

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:

Input: 2, [[1,0]] 
Output: true
Explanation: There are a total of 2 courses to take. 
             To take course 1 you should have finished course 0. So it is possible.
Example 2:

Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take. 
             To take course 1 you should have finished course 0, and to take course 0 you should
             also have finished course 1. So it is impossible.
Note:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
A frog is trying to reach the other side of a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.

If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.

Note:

The number of stones is ≥ 2 and is < 1,100.
Each stone's position will be a non-negative integer < 231.
The first stone's position is always 0.
Example 1:

[0,1,3,5,6,8,12,17]

There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.

Return true. The frog can jump to the last stone by jumping 
1 unit to the 2nd stone, then 2 units to the 3rd stone, then 
2 units to the 4th stone, then 3 units to the 6th stone, 
4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:

[0,1,2,3,4,8,9,11]

Return false. There is no way to jump to the last stone as 
the gap between the 5th and 6th stone is too large.

def canCross(self, stones):
        # keep track of the units we can reach from each stone
        # using a dictionary
        units_reached_from_stone = {}
        # add the first stone to the dictionary with an empty set
        # of units we can reach from it
        units_reached_from_stone[stones[0]] = set()
        # iterate through all the stones
        for i in range(1, len(stones)):
            # get the units we can reach from the current stone
            units_reached_from_current_stone = units_reached_from_stone[stones[i]]
            # iterate through all the units we can reach from the
            # current stone
            for unit in units_reached_from_current_stone:
                # check if the unit we can reach from the current stone
                # is within one unit of the next stone
                if stones[i] + unit - 1 in units_reached_from_stone:
                    # if it is, then we can reach the next stone from the
                    # current stone, so add the unit to the set of units we
                    # can reach from the next stone
                    units_reached_from_stone[stones[i] + unit - 1].add(unit - 1)
                # check if the unit we can reach from the current stone
                # is the same as the unit of the next stone
                if stones[i] + unit in units_reached_from_stone:
                    # if it is, then we can reach the next stone from the
                    # current stone, so add the unit to the set of units we
                    # can reach from the next stone
                    units_reached_from_stone[stones[i] + unit].add(unit)
                # check if the unit we can reach from the current stone
                # is one unit more than the unit of the next stone
                if stones[i] + unit + 1 in units_reached_from_stone:
                    # if it is, then we can reach the next stone from the
                    # current stone, so add the unit to the set of units we
                    # can reach from the next stone
                    units_reached_from_stone[stones[i] + unit + 1].add(unit + 1)
        # return whether or not we can reach the last stone from the
        # first stone
        return len(units_reached_from_stone[stones[-1]]) > 0
There are many ways to solve this problem. One approach would be to use a dynamic programming approach, where we keep track of the earliest time at which we can reach each position. Then, we can iterate over all the positions and check whether we can reach the end position from that position.

var canJump = function(nums) {
  // keep track of the earliest time at which we can reach each position
  var earliest = new Array(nums.length).fill(0);
  // we can reach the first position immediately
  earliest[0] = 0;
  
  // iterate over all the positions
  for (var i = 0; i < nums.length; i++) {
    // check whether we can reach the end position from the current position
    if (i + nums[i] >= nums.length - 1) {
      return true;
    }
    
    // iterate over all the positions that we can reach from the current position
    for (var j = 1; j <= nums[i]; j++) {
      // if the earliest time at which we can reach the current position is later than the earliest time at which we can reach the position that we can reach from the current position, update the earliest time
      if (earliest[i] > earliest[i + j]) {
        earliest[i + j] = earliest[i];
      }
    }
    
    // update the earliest time at which we can reach the current position
    earliest[i]++;
  }
  
  // we can't reach the end position
  return false;
};
There are many ways to solve this problem, but one way to do it is as follows:

1) Start at the beginning of the array and keep track of the maximum index that can be reached from the current index.

2) If the maximum index is less than the end of the array, return false.

3) If the maximum index is greater than or equal to the end of the array, return true.
using System; 
  
class GFG { 
      
// A utility function to check 
// whether destination cell has 
// been reached or not 
static bool isDestination(int x, 
                          int y, int destX, 
                          int destY) 
{ 
    if (x == destX && y == destY) 
        return true; 
    return false; 
} 
  
// A utility function to calculate 
// minimum number of jumps 
// needed to reach destination 
static int minJumps(int arr[], int N, 
                    int currX, int currY, 
                    int destX, int destY) 
{ 
      
    // Base case: If destination is reached 
    if (isDestination(currX, currY, destX, destY)) 
        return 0; 
  
    // If the frog is not on the grid or 
    // if the frog is already on the destination 
    // cell 
    if (currX >= N || currX < 0 || 
        currY >= N || currY < 0 || 
        arr[currX * N + currY] == 0 || 
        arr[currX * N + currY] == 1) 
        return Integer.MAX_VALUE; 
  
    // Mark the current cell as visited 
    arr[currX * N + currY] = 1; 
  
    // Calculate distance of the current 
    // cell from the destination 
    int dist = (Math.abs(currX - destX) + 
                Math.abs(currY - destY)); 
  
    // Find all the possible directions 
    // from the current cell and recur 
    // for each valid direction 
    if (currY + 1 < N) 
        return minJumps(arr, N, currX, currY + 1, 
                        destX, destY); 
    if (currY - 1 >= 0) 
        return minJumps(arr, N, currX, currY - 1, 
                        destX, destY); 
    if (currX + 1 < N) 
        return minJumps(arr, N, currX + 1, currY, 
                        destX, destY); 
    if (currX - 1 >= 0) 
        return minJumps(arr, N, currX - 1, currY, 
                        destX, destY); 
  
    // If none of the directions work 
    // then return MAX_INT as the 
    // solution is not possible 
    return Integer.MAX_VALUE; 
} 
  
// Driver code 
public static void Main() 
{ 
    int N = 4; 
  
    // To store the value of minimum 
    // number of jumps 
    int minJumps = 0; 
  
    // Source coordinates 
    int srcX = 0, srcY = 0; 
  
    // Destination coordinates 
    int destX = 3, destY = 0; 
  
    // To store all the possible 
    // destinations from the source 
    int[][] dest = new int[][] 
    { 
        { 3, 0 }, { 3, 1 }, { 3, 2 }, 
        { 3, 3 } 
    }; 
  
    // To store the value of minimum 
    // number of jumps needed to 
    // reach each destination 
    int[] minJump = new int[dest.length]; 
  
    // Consider each destination 
    // and calculate the minimum 
    // number of jumps needed to 
    // reach it from the source 
    for (int i = 0; i < dest.length; i++) { 
          
        // Calculate minimum number of 
        // jumps needed to reach 
        // dest[i][0], dest[i][1] 
        // from source 
        minJumps = minJumps(arr, N, srcX, 
                            srcY, dest[i][0], 
                            dest[i][1]); 
  
        // If destination can't be reached 
        // then set minJump[i] as -1 
        if (minJumps == Integer.MAX_VALUE) 
            minJump[i] = -1; 
        else
            minJump[i] = minJumps; 
    } 
  
    // Print the minimum number of 
    // jumps needed to reach 
    // each destination from source 
    for (int i = 0; i < minJump.length; i++) { 
        System.out.println(minJump[i]); 
    } 
} 
} 
  
// This code is contributed by 29AjayKumar


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]