본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 657. Robot Return to Origin

반응형

https://leetcode.com/problems/robot-return-to-origin/description/

 

Robot Return to Origin - LeetCode

Can you solve this real interview question? Robot Return to Origin - There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. You are giv

leetcode.com

simulation 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. U, D, L, R의 움직임에 맞도록 행 dr, 열 dc를 선언해 값을 저장해 줍니다.2. 처음 (0,0)을 r,c변수를 선언해 초기화해 줍니다.

📔 풀이과정

moves에 대해 for loop를 돌며 움직임에 맞도록 r, c값을 갱신해줍니다.

📔 정답 출력 | 반환

r과 c가 둘다 0인지 여부를 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    //U, D, L, R
    int dr[4] = {-1, 1, 0, 0};
    int dc[4] = {0, 0, -1, 1};
    bool judgeCircle(string moves) {
        int r = 0, c = 0;
        for(auto m : moves) {
            if(m == 'U') r += dr[0], c += dc[0];
            if(m == 'D') r += dr[1], c += dc[1];
            if(m == 'L') r += dr[2], c += dc[2];
            if(m == 'R') r += dr[3], c += dc[3];
        }
        return !r && !c;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.