Re: [閒聊] 每日leetcode

作者: dont   2024-09-04 10:58:55
874. Walking Robot Simulation
## 思路
先把obstacles改為set 方便檢查
然後模擬
記錄command移動後的最大距離平方和
## Code
```python
class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) ->
int:
obstacles = {(x, y) for x, y in obstacles}
res = 0
x = y = i = 0
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for cmd in commands:
if cmd == -1:
i = (i+1) % 4
elif cmd == -2:
i = (i-1) % 4
else:
for _ in range(cmd):
nx, ny = x + dirs[i][0], y + dirs[i][1]
if (nx, ny) in obstacles:
break
x, y = nx, ny
res = max(res, x * x + y * y)
return res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com