C++ code to check grasshopper can reach target or not

C++Server Side ProgrammingProgramming

Suppose we have a string S of size n and another number k. The string contains four types of characters. Consider there are few cells, a grasshopper wants to jump to reach the target. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. 'G' means that the grasshopper starts at this position and, 'T' means that the target cell. The grasshopper is able to jump exactly k cells away from its current position. We have to check whether the grasshopper can jump to the target or not.

So, if the input is like S = "#G#T#"; k = 2, then the output will be True, because from G to T it is 2 cells away and k is 2 so grasshopper can reach there by a single jump.


To solve this, we will follow these steps −

n := size of S
x := position of 'G' in S
y := position of 'T' in S
if x > y, then:
   swap x and y
for initialize i := x, when i < y, update i := i + k, do:
   if S[i] is same as '#', then:
      Come out from the loop
if i is same as y, then:
   return true
   return false


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
bool solve(string S, int k){
   int n = S.size();
   int i;
   int x = S.find('G');
   int y = S.find('T');
   if (x > y)
      swap(x, y);
   for (i = x; i < y; i += k){
      if (S[i] == '#')
   if (i == y)
      return true;
      return false;
int main(){
   string S = "#G#T#";
   int k = 2;
   cout << solve(S, k) << endl;


"#G#T#", 2


Updated on 29-Mar-2022 09:10:54