在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方。机器人可以接受下列三条指令之一:
只有在平面中存在环使得机器人永远无法离开时,返回 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'} 中
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/robot-bounded-in-circle 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
4次循环指令后,能回到原点,就永远走不出去
class Solution {
public:
bool isRobotBounded(string instructions) {
vector<vector<int>> dir = {{0,1},{1,0},{0,-1},{-1,0}};
int x = 0, y = 0, d = 0, n = 4;
while(n--)
for(char ch : instructions)
{
if(ch == 'G')
{
x += dir[d][0];
y += dir[d][1];
}
else if(ch == 'L')
d = (d-1+4)%4;
else
d = (d+1)%4;
}
return x==0 && y==0;
}
};
4 ms 6.2 MB
或者是,一次指令后,在原点,或者方向变了,就一定能再走回来。
class Solution {
public:
bool isRobotBounded(string instructions) {
vector<vector<int>> dir = {{0,1},{1,0},{0,-1},{-1,0}};
int x = 0, y = 0, d = 0, n = 4;
for(char ch : instructions)
{
if(ch == 'G')
{
x += dir[d][0];
y += dir[d][1];
}
else if(ch == 'L')
d = (d-1+4)%4;
else
d = (d+1)%4;
}
return (x==0 && y==0) || d!=0;
}
};
4 ms 6.5 MB