
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ code to find minimum jump to reach home by frog
Suppose we have one binary string S with n bits and another number d. On a number line, a frog wants to reach point n, starting from the point 1. The frog can jump to the right at a distance not more than d. For each point from 1 to n if there is a lily flower it is marked as 1, and 0 if not. The frog can jump only in points with a lilies. We have to find the minimal number of jumps that the frog needs to reach n. If not possible, return -1.
So, if the input is like S = "10010101"; d = 4, then the output will be 2, because from position 1, it jumps to 4, then at the index 8(n).
Steps
To solve this, we will follow these steps −
n := size of s x := 0 y := 0 while (x < n - 1 and y <= n), do: if s[x] is same as '1', then: x := x + d increase y by 1 Otherwise (decrease x by 1) if y >= n, then: return -1 Otherwise return y
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(string s, int d){ int n = s.size(); int x = 0, y = 0; while (x < n - 1 && y <= n){ if (s[x] == '1') x += d, ++y; else --x; } if (y >= n) return -1; else return y; } int main(){ string S = "10010101"; int d = 4; cout << solve(S, d) << endl; }
Input
"10010101", 4
Output
2
- Related Articles
- Program to find minimum jumps to reach home in Python
- Program to find minimum jump needed to return from a folder to home in Python
- Frog Jump in C++
- C++ code to count steps to reach final position by robot
- Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps in Python
- Program to find minimum steps to reach target position by a chess knight in Python
- Count number of ways to jump to reach end in C++
- Find the minimum cost to reach destination using a train
- How to find the minimum number of steps needed by knight to reach the destination using C#?
- C++ code to find minimum arithmetic mean deviation
- Minimum Initial Points to Reach Destination
- C++ code to find minimum different digits to represent n
- C++ code to find minimum difference between concerts durations
- C++ code to find minimum stones after all operations
- Program to find number of minimum steps to reach last index in Python

Advertisements