Re: [闲聊] 每日leetcode

楼主: JerryChungYC (JerryChung)   2024-09-04 11:10:50
https://leetcode.com/problems/walking-robot-simulation
※ 引述《enmeitiryous (enmeitiryous)》之铭言:
: 题目: 874 walking robot simulation
: 一个机器人起始在(0,0)并面向+y的方向,给你一串指令 commands,当coomands[i]=-1代
: 表向右转,-2代表向左转,否则代表朝面向方向走的距离,给你一个blockers座标vector
: 如果机器人的下一步存在该列表中则机器人原地停下,求在过程中最大的x**2+y**2
: 思路:
: 照做,先把blockers塞到一个set,每一次移动时看下一步是不是在blockers中,并记录
: 每一次移动完x**2+y**2需不需要更新
思路:差不多
Python Code:
class Solution:
def robotSim(self,commands: List[int],obstacles: List[List[int]]) -> int:
arr = ((0, 1), (-1, 0), (0, -1), (1, 0))
idx = 0
now = (0, 0)
ans = 0
obstacles_set = set(tuple(obs) for obs in obstacles)
for command in commands:
if command == -1:
idx -= 1
idx %= 4
elif command == -2:
idx += 1
idx %= 4
else:
while command:
x, y = now[0] + arr[idx][0], now[1] + arr[idx][1]
if (x, y) in obstacles_set:
break
now = (x, y)
command -= 1
ans = max(ans, now[0] ** 2 + now[1] ** 2)
return ans
先转为 set 再搜寻
原本用 list 直接 6000ms 接 TLE
set 就快很多了
距离则等当次走完再算就好

Links booklink

Contact Us: admin [ a t ] ucptt.com