알고리즘/해결

LeetCode657. Robot Return to Origin

언클린 2020. 3. 18. 20:22
728x90

1. 문제(원본)

There is a robot starting at 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.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Example 1:

Input: "UD" Output: true Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

 

Example 2:

Input: "LL" Output: false Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.

2. 문제

로봇의 움직임이 끝났을 때에 원점인지 (0,0) 확인하라 

3. 나의 답

class Solution {

    func judgeCircle(_ moves: String) -> Bool {

        var x = 0

        var y = 0

 

        moves.forEach { (c) in

            switch c {

            case "U": y -= 1

            case "D": y += 1

            case "L": x -= 1

            case "R": x += 1

            default: break

            }

        }

        return (x >= 0 && y >= 0)

    }

}

4. 다른 유저의 답

#1

class Solution {

    func judgeCircle(_ moves: String) -> Bool {

        var x = 0

        var y = 0

        

        moves.forEach { c in

            

            switch c {

            case "R": x += 1

            case "L": x -= 1

            case "U": y += 1

            case "D": y -= 1

            default: x += 0; y += 0

            }

        }

        

        return x == 0 && y == 0

    }

}

5. 마무리

이번 문제는 거의 모든 유저들의 답이 비슷했다. 어렵진 않았지만 처음에 문제를 잘못 이해해 오류를 많이 범했다.

(원점일 경우가 아니라 이동할 수 없는 경우를 구해버렸다...)

문제를 잘 읽고 이해하는 것도 중요한 것을 알 수 있는 문제였다.

 

728x90