[leetcode] 1041. Robot Bounded In Circle
原创
©著作权归作者所有:来自51CTO博客作者是念的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description
On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
- “G”: go straight 1 unit;
- “L”: turn 90 degrees to the left;
- “R”: turn 90 degress to the right.
The robot performs the instructions given in order, and repeats them forever.
Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.
Example 1:
Input: "GGLLGG"
Output: true
Explanation:
The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
Example 2:
Input: "GG"
Output: false
Explanation:
The robot moves north indefinitely.
Example 3:
Input: "GL"
Output: true
Explanation:
The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
Note:
- 1 <= instructions.length <= 100
- instructions[i] is in {‘G’, ‘L’, ‘R’}
分析
题目的意思是:机器人按照instructions指令循环的走,如果出现了环则返回True,否则返回False。这道题我题目没看懂,后面发现instructions就是命令,机器人需要重复执行,这里有一个规律,如果机器人执行了4次instructions回到了原点的话,说明出现了还了,机器人永远也走不出去了;否则就能走出去。出现L的时候,明显要向左。
x,y代表机器人的位置,all_direction代表方向,距离’GL’,其走过的路线如下:
可以模拟试试看
代码
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
d=0
x=0
y=0
all_direction = [[0,1],[-1,0],[0,-1],[1,0]] #向北,向左,向南,向右
for j in range(4):
for i in instructions:
if(i=='L'):
d-=1
elif(i=='R'):
d+=1
else:
x+=all_direction[d%4][0]
y+=all_direction[d%4][1]
return x==0 and y==0
代码二
class Solution:
def isRobotBounded(self, instructions: str):
d=0
x=0
y=0
all_direction = [[0,1],[1,0],[0,-1],[-1,0]] # 方向: 0上 1右 2下 3左
for j in range(4):
for i in instructions:
if(i=='L'):
d-=1
elif(i=='R'):
d+=1
else:
x+=all_direction[d%4][0]
y+=all_direction[d%4][1]
print(x,y)
return x==0 and y==0
if __name__ == "__main__":
solution=Solution()
s='GL'
res=solution.isRobotBounded(s)
print(res)
参考文献
solution