Robot Bounded In Circle

On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions:

  • "G": go straight 1 unit;
  • "L": turn 90 degrees to the left;
  • "R": turn 90 degress to the right.

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.

Example 1:

Input: "GGLLGG"
Output: true
Explanation: 
The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.

思路:这题应该是个hard难度,终点状态比较难想:

终点,只要是

第一:回到原点了,那肯定是cycle。

第二,如果面向还是north,但是坐标变了,不是0,0了,那么就是在shift,那么肯定不是cycle;其余状态肯定是cycle;

另外,跟robot那题一样,向左向右,dx一定要有顺序,顺时针,这样好判断direction;(direction + k) % 4;

class Solution {
    public boolean isRobotBounded(String instructions) {
        int[] pos = new int[] {0, 0};
        int[] dx = {1, 0, -1, 0}; // 上左下右
        int[] dy = {0, 1, 0, -1};
        int dir = 0;
        for(int i = 0; i < instructions.length(); i++) {
            char c = instructions.charAt(i);
            if(c == 'L') {
                dir = (dir + 3) % 4;
            } else if(c == 'R') {
                dir = (dir + 1) % 4;
            } else {
                // c == 'G';
                pos[0] = pos[0] + dx[dir];
                pos[1] = pos[1] + dy[dir];
            }
        }
        if(pos[0] == 0 && pos[1] == 0) {
            return true;
        }
        if(dir == 0 && !(pos[0] == 0 && pos[1] == 0)) {
            return false;
        }
        return true;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值