C++程式碼檢查蚱蜢能否到達目標


假設我們有一個大小為n的字串S和另一個數字k。該字串包含四種類型的字元。假設有一些單元格,一隻蚱蜢想要跳躍以到達目標。字元“.”表示相應的單元格為空,字元“#”表示相應的單元格包含障礙物,蚱蜢不能跳到那裡。“G”表示蚱蜢從該位置開始,“T”表示目標單元格。蚱蜢能夠從其當前位置跳躍正好k個單元格。我們必須檢查蚱蜢是否可以跳到目標。

因此,如果輸入類似於S = "#G#T#"; k = 2,則輸出將為True,因為從G到T有2個單元格,而k為2,所以蚱蜢可以透過一次跳躍到達那裡。

步驟

為了解決這個問題,我們將遵循以下步驟:

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
Otherwise
   return false

示例

讓我們看看以下實現以獲得更好的理解:

#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] == '#')
         break;
   }
   if (i == y)
      return true;
   else
      return false;
}
int main(){
   string S = "#G#T#";
   int k = 2;
   cout << solve(S, k) << endl;
}

輸入

"#G#T#", 2

輸出

1

更新於: 2022年3月29日

247 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.