1041 困于环中的机器人

题目描述:
在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方。机器人可以接受下列三条指令之一:
“G”:直走 1 个单位
“L”:左转 90 度
“R”:右转 90 度
机器人按顺序执行指令 instructions,并一直重复它们。
只有在平面中存在环使得机器人永远无法离开时,返回 true。否则,返回 false。

示例 1:
输入:“GGLLGG”
输出:true
解释:
机器人从 (0,0) 移动到 (0,2),转 180 度,然后回到 (0,0)。
重复这些指令,机器人将保持在以原点为中心,2 为半径的环中进行移动。

示例 2:
输入:“GG”
输出:false
解释:
机器人无限向北移动。

示例 3:
输入:“GL”
输出:true
解释:
机器人按 (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> … 进行移动。

提示:
1 <= instructions.length <= 100
instructions[i] 在 {‘G’, ‘L’, ‘R’} 中

方法1:
主要思路:解题链接汇总
(1)只要保证遍历一遍之后,最后的位置是起始位置(0,0)或者最后位置的方向和起始的方向不一致,就存在环,使机器人用于困在平面之内;

class Solution {
public:
    bool isRobotBounded(string instructions) {
        int dir=0;//0,1,2,3表示上,右,下,左四个方向
        vector<vector<int>> steps={{1,0},{0,1},{-1,0},{0,-1}};//四个方向下,移动的步距
        int cur_r=0,cur_c=0;//每个移动的位置
        for(char&ch:instructions){	
        	//三种不同的指令
            if(ch=='L'){
                dir=(dir-1+4)%4;
            }
            else if(ch=='R'){
                dir=(dir+1)%4;
            }
            else{
                cur_r+=steps[dir][0];
                cur_c+=steps[dir][1];
            }
        }
        //判断最后的状态
        return (cur_r==0&&cur_c==0)||(dir!=0);
    }
};

方法2:
主要思路:
(1)和上述一致,代码使用go

func isRobotBounded(instructions string) bool {
    dir := 0
    steps := [4][2]int{{1,0},{0,1},{-1,0},{0,-1}}
    cur_r := 0
    cur_c := 0
    len_str := len(instructions)
    for i := 0;i < len_str;i++ {
        if instructions[i] == 'L' {
            dir = (dir - 1 + 4) % 4
        }else if instructions[i] == 'R' {
            dir = (dir + 1) % 4
        }else{
            cur_r += steps[dir][0]
            cur_c += steps[dir][1]
        }
    }
    return (cur_r == 0 && cur_c == 0)||(dir != 0)
}

你可能感兴趣的:(LeetCode)