Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

1041. Robot Bounded In Circle 🌟🌟

No.1 Most asked amazon question of the year 2021-Leetcode premium/

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

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.

Simulation

Code

class Solution {
public:
    bool isRobotBounded(string instructions)
    {
        int dirX = 0, dirY = 1;
        int x = 0, y = 0;
        int temp = 0;
        for (auto& d : instructions) {
            if (d == 'G') {
                x += dirX;
                y += dirY;
            } else if (d == 'L') {
                temp = dirX;
                dirX = -dirY;
                dirY = temp;
            } else {
                temp = dirX;
                dirX = dirY;
                dirY = -temp;
            }
        }
        return ((x == 0 && y == 0) || (dirX != 0 || dirY != 1));
    }
};