Leetcode 1041. 困于环中的机器人
本文最后更新于413 天前,其中的信息可能已经过时,如有错误请发送邮件到2446865563@qq.com

1.题目基本信息

1.1.题目描述

在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方。注意:

  • 北方向 是y轴的正方向。
  • 南方向 是y轴的负方向。
  • 东方向 是x轴的正方向。
  • 西方向 是x轴的负方向。

机器人可以接受下列三条指令之一:

  • "G":直走 1 个单位
  • "L":左转 90 度
  • "R":右转 90 度

机器人按顺序执行指令 instructions,并一直重复它们。

只有在平面中存在环使得机器人永远无法离开时,返回 true。否则,返回 false。

1.2.题目地址

https://leetcode.cn/problems/robot-bounded-in-circle/description

2.解题方法

2.1.解题思路

模拟:只有一种情况,机器人无限循环下不能到达起点,即为假如开始是向北走,那么一次循环后,机器人不在起点并且方向还是向北。其余情况经过有限次循环,都能到达起点。

2.2.解题步骤

第一步,构建方向数组并初始化当前的方向和位置

第二步,遍历步骤,并更新当前的方向和位置

第三步,根据一次循环后的位置和方向判断无限循环下是否能到达起点

3.解题代码

Python代码

class Solution:
    # 模拟:只有一种情况,机器人无限循环下不能到达起点,即为假如开始是向北走,那么一次循环后,机器人不在起点并且方向还是向北。其余情况经过有限次循环,都能到达起点。
    def isRobotBounded(self, instructions: str) -> bool:
        # 第一步,构建方向数组并初始化当前的方向和位置
        directions=[[0,1],[-1,0],[0,-1],[1,0]]
        directIndex=0
        x,y=0,0
        # 第二步,遍历步骤,并更新当前的方向和位置
        for c in instructions:
            if c=="G":
                x+=directions[directIndex][0]
                y+=directions[directIndex][1]
            elif c=="L":
                directIndex=(directIndex+1)%4
            elif c=="R":
                directIndex=(directIndex-1)%4
        # 第三步,根据一次循环后的位置和方向判断无限循环下是否能到达起点
        return False if directIndex==0 and (x!=0 or y!=0) else True

C++代码

class Solution {
public:
    bool isRobotBounded(string instructions) {
        vector<vector<int>> directions={{0,1},{-1,0},{0,-1},{1,0}};
        int directIndex=0;
        int x=0,y=0;
        for(char c:instructions){
            if(c=='G'){
                x+=directions[directIndex][0];
                y+=directions[directIndex][1];
            }else if(c=='L'){
                directIndex=(directIndex+1)%4;
            }else if(c=='R'){
                directIndex=(directIndex-1+4)%4;
            }
        }
        return directIndex==0 && (x!=0 || y!=0) ? false : true;
    }
};

4.执行结果

觉得有帮助可以投喂下博主哦~感谢!

作者:geek007

转载请注明文章地址及作者哦~
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇