用 C++ 程式尋找點


假設我們有一個起始點 (sx, sy),和目標點 (tx, ty),我們必須檢查從起始點到終點是否存在一系列移動。此處的移動包括取一個點 (x, y) 並將其轉換為 (x, x+y) 或 (x+y, y)。

因此,如果輸入是 (1, 1) 和 (4,5),則答案將為真,這是因為將 (1,1) 移動到 (2,1),然後到 (3,1),然後到 (4,1),然後到 (4,5)。

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

  • 當 tx > sx 且 ty > sy 時執行以下操作:
    • 如果 tx > ty,則:
      • tx := tx mod ty
    • 否則
      • ty := ty mod tx
  • 返回(當 sx 與 tx 相同且 sy <= ty 且 (ty - sy) mod tx 與 0 相同時為 true)或(當 sy 與 ty 相同且 x >= sx 且 (tx - sx) mod ty 為 0 時為 true)

為了更好地理解,讓我們看看以下實現:

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool reachingPoints(int sx, int sy, int tx, int ty) {
      while(tx > sx && ty > sy){
         if(tx > ty){
            tx %= ty;
         }else ty %= tx;
      }
      return (sx == tx && sy <= ty && (ty - sy) % tx == 0) || (sy == ty && tx >= sx && (tx - sx) % ty == 0);
   }
};
main(){
   Solution ob;
   cout << (ob.reachingPoints(1,1,4,5));
}

輸入

1
1
4
5

輸出

1

更新於: 02-6 月 2020

148 次瀏覽

開啟你的職業生涯

獲得認證,完成課程

立即開始
廣告
© . All rights reserved.