Python步行機器人模擬


假設在一個無限網格上有一個機器人,它從點 (0, 0) 出發。它面向北方。現在機器人可以接收三種可能的命令型別:

  1. -2:向左轉 90 度
  2. -1:向右轉 90 度
  3. 1 到 9 之間的任何值:向前移動 x 個單位
  4. 有一些網格方塊是障礙物。

我們還有一個名為 obstacle 的陣列,它指示第 i 個障礙物位於網格點 (obstacles[i][0], obstacles[i][1]),如果機器人想要移動到它們上面,機器人將停留在之前的網格方塊。

我們必須找到機器人到原點的最大歐幾里得距離的平方。

因此,如果輸入類似於 commands = [4,-1,4,-2,4], obstacles = [[2,4]],則輸出將為 65,因為機器人將在向左轉並移動到 (1, 8) 之前卡在 (1, 4) 處。

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

  • position_offset := [(0, 1) ,(1, 0) ,(0, -1) ,(-1, 0) ]
  • 初始化 x、y、direction、max_distance 為 0
  • 對於 commands 中的每個命令,執行:
    • 如果命令等於 -2,則
      • direction := (direction - 1) mod 4
    • 否則,如果命令等於 -1,則
      • direction := (direction + 1) mod 4
    • 否則,
      • (x_off, y_off) := position_offset[direction]
    • 當命令不為零時,執行:
      • 如果 (x + x_off, y + y_off) 不在 obstacles 中,則
        • x := x + x_off
        • y := y + y_off
      • command := command - 1
    • max_distance = max_distance, x^2 + y^2 的最大值
  • 返回 max_distance

讓我們看看下面的實現來更好地理解:

示例

 線上演示

class Solution:
   def robotSim(self, commands, obstacles):
      position_offset = [(0, 1), (1, 0), (0, -1), (-1, 0)]
      obstacles = set(map(tuple, obstacles))
      x, y, direction, max_distance = 0, 0, 0, 0
      for command in commands:
         if command == -2: direction = (direction - 1) % 4
            elif command == -1: direction = (direction + 1) % 4
               else:
                  x_off, y_off = position_offset[direction]
                  while command:
                     if (x + x_off, y + y_off) not in obstacles:
                        x += x_off
                        y += y_off
                     command -= 1
                  max_distance = max(max_distance, x**2 + y**2)
      return max_distance
ob = Solution()
print(ob.robotSim([4,-1,4,-2,4],[[2,4]]))

輸入

[4,-1,4,-2,4],[[2,4]]

輸出

65

更新於:2020年7月4日

863 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.