DEV Community

Wenqi Jiang
Wenqi Jiang

Posted on

1041. Robot Bounded In Circle

Description

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 degrees 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: instructions = "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.
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: instructions = "GG"
Output: false
Explanation: The robot moves north indefinitely.
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: instructions = "GL"
Output: true
Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • 1 <= instructions.length <= 100
  • instructions[i] is 'G''L' or, 'R'.

Solutions

Solution 1

Intuition

if back to start point or direction is not to up/north after one set of instructions, it means it returns true

Code

class Solution {

    private final int[][] DIRECTIONS = new int[][] {
            { 1, 0 }, // up
            { 0, 1 }, // right
            { -1, 0 }, // down
            { 0, -1 }// left
    };

    public boolean isRobotBounded(String instructions) {
        // start point
        int x = 0, y = 0;
        // default direction index is 0, means go up
        int index = 0;
        for (char instruction : instructions.toCharArray()) {
            switch (instruction) {
                case 'L':
                    // index = 3 means go left
                    index = (index + 3) % 4;
                    break;
                case 'R':
                    // index = 1 means go right
                    index = (index + 1) % 4;
                    break;
                default:
                    // move towards direction
                    x += DIRECTIONS[index][0];
                    y += DIRECTIONS[index][1];
            }
        }
        // back start point or direction is not go up
        return x == 0 && y == 0 || index != 0;
    }
}
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(n)
  • Space: O(1)

Top comments (0)