[leetcode] 1041. Robot Bounded In Circle

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. 1 <= instructions.length <= 100
  2. instructions[i] is in {‘G’, ‘L’, ‘R’}

分析

题目的意思是:机器人按照instructions指令循环的走,如果出现了环则返回True,否则返回False。这道题我题目没看懂,后面发现instructions就是命令,机器人需要重复执行,这里有一个规律,如果机器人执行了4次instructions回到了原点的话,说明出现了还了,机器人永远也走不出去了;否则就能走出去。出现L的时候,明显要向左。
x,y代表机器人的位置,all_direction代表方向,距离’GL’,其走过的路线如下:

0 1
-1 1
-1 0
0 0
True

可以模拟试试看

代码

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值