Computer Science/알고리즘

leetcode 1041) Robot Bounded In Circle

eeeun:) 2022. 1. 9. 19:15
반응형

LV. Medium 🧐

https://leetcode.com/problems/robot-bounded-in-circle/description/

 

Robot Bounded In Circle - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제

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.

Example 2:

Input: instructions = "GG"
Output: false
Explanation: The robot moves north indefinitely.

Example 3:

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

 

Constraints:

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

 

문제 해결법

로봇이 평면 안에서 원을 그려야되니깐, 무조건 처음 위치인 (0, 0)으로 돌아와야함!

한 싸이클에서 0도, 360도 돈다면 -> 한 싸이클이 끝났을 때 위치가 (0, 0)
90도를 돈다면 360까지 도는데 4 싸이클이 필요 -> 4 싸이클 끝났을 때 위치가 (0, 0)
180도를 돈다면 360까지 도는데 2 싸이클이 필요 -> 2 싸이클 끝났을 때 위치가 (0, 0)
270도를 돈다면 360의 배수까지 도는데 4 싸이클이 필요 -> 4싸이클 끝났을 때 위치가 (0, 0)

0도, 90도, 180도, 270도, 360도를 찾아 다르게 계산해주기 복잡하므로 그냥 4싸이클 후에 (0, 0)인지 확인해줌!

 

해결 코드
#define NORTH 0
#define WEST 1
#define SOUTH 2
#define EAST 3

class Robot{
private:
	int x;
	int y;
	int dir;

public:
	Robot() : x(0), y(0), dir(0) {
	}
	int getX() {
		return x;
	}
	int getY() {
		return y;
	}
	void turnLeft() {
		dir = dir == 0 ? 3 : dir - 1;
	}
	void turnRight() {
		dir = (dir + 1) % 4;
	}
	void go() {
		if (NORTH == dir)
			y++;
		else if (WEST == dir)
			x--;
		else if (SOUTH == dir)
			y--;
		else if (EAST == dir)
			x++;
	}
};

class Solution {
public:
	bool isRobotBounded(string instructions) {
		int i = -1;
		Robot robot;

		for (int j = 0; j < 4; ++j) {
			i = -1;
			while (instructions[++i]) {
				if (instructions[i] == 'L')
					robot.turnLeft();
				else if (instructions[i] == 'R')
					robot.turnRight();
				else
					robot.go();
			}
		}
		return robot.getX() == 0 && robot.getY() == 0;
	}
};

728x90