Skip to content

Commit 66a5104

Browse files
committedNov 24, 2020
feat: walking-robot-simulation
1 parent 37d5d8d commit 66a5104

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
 

‎greedy.walking-robot-simulation.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
874. 模拟行走机器人
7+
https://leetcode-cn.com/problems/walking-robot-simulation/description/
8+
机器人在一个无限大小的网格上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令:
9+
-2:向左转 90 度
10+
-1:向右转 90 度
11+
1 <= x <= 9:向前移动 x 个单位长度
12+
在网格上有一些格子被视为障碍物。
13+
第 i 个障碍物位于网格点  (obstacles[i][0], obstacles[i][1])
14+
机器人无法走到障碍物上,它将会停留在障碍物的前一个网格方块上,但仍然可以继续该路线的其余部分。
15+
返回从原点到机器人所有经过的路径点(坐标为整数)的最大欧式距离的平方。
16+
"""
17+
18+
def robotSim(self, commands, obstacles):
19+
# 向北 0,1 向南 0,-1
20+
dx = [0, 1, 0, -1]
21+
# 向东 1,0,向西 -1, 0
22+
dy = [1, 0, -1, 0]
23+
x = y = di = 0
24+
obstacleSet = set(map(tuple, obstacles))
25+
ans = 0
26+
27+
for cmd in commands:
28+
# 左转
29+
if cmd == -2:
30+
di = (di - 1) % 4
31+
# 右转,则改变纵坐标
32+
elif cmd == -1: # right
33+
di = (di + 1) % 4
34+
else:
35+
# 遍历本次步数
36+
for k in range(cmd):
37+
# 判断当前走到的位数是否不在障碍物中
38+
if (x + dx[di], y + dy[di]) not in obstacleSet:
39+
# 向前移动
40+
x += dx[di]
41+
y += dy[di]
42+
ans = max(ans, x * x + y * y)
43+
44+
return ans
45+
46+
47+
so = Solution()
48+
print(so.robotSim([4, -1, 3], []))
49+
print(so.robotSim([4, -1, 4, -2, 4], [[2, 4]]))
50+

0 commit comments

Comments
 (0)
Please sign in to comment.