LeetCode 1041

题目描述:

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;
        
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值