Python 程式檢查機器人能否到達目標位置


假設我們有一個機器人,目前位於 (0, 0) 位置(笛卡爾平面)。如果我們有一系列它可以執行的移動,包含 N(北)、S(南)、W(西)和 E(東)。我們必須檢查它是否可以到達目標座標 (x, y)。

因此,如果輸入類似於 moves = ['N','N','E','E','S'], (x,y) = (2,1),則輸出為 True。

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

  • temp_coord := [0,0]
  • 對於 moves 中的每個移動,執行以下操作:
    • 如果 move 等於 "N",則
      • temp_coord[1] := temp_coord[1] + 1
    • 否則,如果 move 等於 "S",則
      • temp_coord[1] := temp_coord[1] - 1
    • 否則,如果 move 等於 "E",則
      • temp_coord[0] := temp_coord[0] + 1
    • 否則,如果 move 等於 "W",則
      • temp_coord[0] := temp_coord[0] - 1
  • 如果 temp_coord[0] 等於 coord[0] 且 temp_coord[1] 等於 coord[1],則返回 True,否則返回 false。

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

示例

 線上演示

class Solution:
   def solve(self, moves, coord):
      temp_coord = [0,0]
      for move in moves:
         if move == "N":
            temp_coord[1] += 1
         elif move == "S":
            temp_coord[1] -= 1
         elif move == "E":
            temp_coord[0] += 1
         elif move == "W":
            temp_coord[0] -= 1
      return temp_coord[0] == coord[0] and temp_coord[1] == coord[1]
ob = Solution()
moves = ['N','N','E','E','S']
coord = [2,1]
print(ob.solve(moves, coord))

輸入

['N','N','E','E','S'], [2,1]

輸出

True

更新於: 2020年10月7日

363 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.