机器人在一个无限大小的 XY 网格平面上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令 commands : -2 :向左转 90 度 -1 :向右转 90 度 1 <= x <= 9 :向前移动 x 个单位长度 在网格上有一些格子被视为障碍物 obstacles 。第 i 个障碍物位于网格点 obstacles[i] = (xi, yi) 。 机器人无法走到障碍物上,它将会停留在障碍物的前一个网格方块上,并继续执行下一个命令。 返回机器人距离原点的 最大欧式距离的平方 。(即,如果距离为 5 ,则返回 25 )
class Solution:
def __init__(self):
"""initialization"""
self.d = 0 # direction sign
self.rot = [-1, -2] # rotation
self.org = [0, 0] # origin
self.dir = [[0, 1], [1, 0], [0, -1], [-1, 0]] # direction
def robotSim(self, commands, obstacles):
x, y = self.org
max_distance = 0
obstacle_set = set(map(tuple, obstacles))
for command in commands:
if command in self.rot:
if command == -1:
self.d = (self.d + 1) % 4
else:
self.d = (self.d - 1) % 4
else:
for _ in range(command):
dx, dy = self.dir[self.d]
if (x + dx, y + dy) in obstacle_set:
break
else:
x += dx
y += dy
distance = x**2 + y**2
if distance > max_distance:
max_distance = distance
return max_distance
if __name__ == '__main__':
Solution = Solution()
# commands = [6,-1,-1,6]
# obstacles = []
# print(Solution.robotSim(commands=commands, obstacles=obstacles))
#
# commands = [4, -1, 3]
# obstacles = []
# print(Solution.robotSim(commands, obstacles)) # 输出: 25
commands = [4, -1, 4, -2, 4]
obstacles = [[2, 4]]
print(Solution.robotSim(commands, obstacles)) # 输出: 65
笔记:
1.减少循环、乘法运算可以提高运算速度
2.利用set(map(tuple, obstacles))函数,首先将obstacles内部的数据画成元组,然后化成集合,调用速度更快。