题目描述:
On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:
The north direction is the positive direction of the y-axis.
The south direction is the negative direction of the y-axis.
The east direction is the positive direction of the x-axis.
The west direction is the negative direction of the x-axis.
The robot can receive one of three instructions:
"G": go straight 1 unit.
"L": turn 90 degrees to the left (i.e., anti-clockwise direction).
"R": turn 90 degrees to the right (i.e., clockwise direction).
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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/robot-bounded-in-circle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
将一条指令当作一条边,如果这条指令可以形成闭环,那么最多需要四次执行这条指令可以回到原点。那么我们只需要在执行完这条指令之后判断最后的方向是不是和初始的方向一致,并且位置是否是原点,如果存在这种情况那么就能形成闭环。
代码:
class Solution {
public:
bool isRobotBounded(string instructions) {
vector<vector<int> > dir = {{0,1},{-1,0},{0,-1},{1,0}};
int curDir = 0 ; // 初始的方向
int x = 0 , y = 0;
//把一条指令走的路径当成一条边,那么最多执行四次指令可以回到原点
for(int i = 0 ; i < 4 ; i++)
{
for(auto instruction : instructions)
{
if(instruction == 'L')
curDir = (curDir+1)%4;
else if(instruction == 'R')
curDir = (curDir+3)%4;
else
{
x += dir[curDir][0];
y += dir[curDir][1];
}
}
if(curDir == 0) //当执行的指令最后的方向和初始方向一致的时候,这个时候就有可能回到初始位置
return x==0&&y==0; //方向一致并且位置在原点才能形成闭环
}
return x == 0 && y == 0;
}
};