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.