fix:模拟行走机器人

上级 5a4a332f
"""
模拟行走机器人
"""
from typing import List
class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
# 转为元组
obstacles_set = set(map(tuple, obstacles))
# x和y轴
x, y = 0, 0
# 方向 0北 1东 2南 3西
direction = 0
# 北 东 南 西的顺序
direction_for = [[0, 1], [1, 0], [0, -1], [-1, 0]]
# 结果集
max_result = 0
for command in commands:
# 如果确定direction的方向
if command == -2:
direction = (direction + 3) % 4
elif command == -1:
direction = (direction + 1) % 4
else:
# 每走一步都需要判断是否会遇到障碍物
for i in range(command):
next_x, next_y = x + direction_for[direction][0], y + direction_for[direction][1]
if (next_x, next_y) in obstacles_set:
break
else:
# 需要重置x和y的位置
x, y = next_x, next_y
max_result = max(max_result, next_x ** 2 + next_y ** 2)
return max_result
if __name__ == '__main__':
result = Solution().robotSim([4, -1, 4, -2, 4], [[2, 4]])
print(result)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册