Leetcode657 (water problem) Can the robot return to the origin?

Leetcode657 (water problem) Can the robot return to the origin?

Title description:

On the two-dimensional plane, there is a robot starting from the origin (0, 0). Given its moving sequence, judge whether the robot ends at (0, 0) after completing its movement.
The movement sequence is represented by a character string. The character move[i] represents its i-th move. The effective actions of the robot are R (right), L (left), U (up) and D (down). If the robot returns to the origin after completing all actions, it returns true. Otherwise, it returns false.
Note: The direction the robot "faces" does not matter. "R" will always move the robot to the right once, "L" will always move to the left, etc. In addition, it is assumed that the moving range of the robot is the same each time.

Example 1:

Input: "UD"
Output: true
Explanation: The robot moves up once, then moves down once. All actions have the same amplitude, so it eventually returns to the origin where it started. Therefore, we return true.

Example 2:

Input: "LL"
Output: false
Explanation: The robot moves to the left twice. It is ultimately located on the left side of the origin, two "movements" from the origin. We return false because it did not return to the origin at the end of the movement.

answer:

The initial position of the robot can be regarded as the coordinate origin O, and it is only necessary to judge whether the horizontal offset x and the vertical offset y are 0 when it finally stops. L represents a horizontal offset by 1 unit to the left, R represents a horizontal offset by one unit to the right, U represents a vertical offset by 1 unit, and D represents a vertical offset by 1 unit.

AC code

class Solution {
    
    
public:
    bool judgeCircle(string moves) {
    
    
        int x = 0;
        int y = 0;
        for(auto& move : moves){
    
    
            if(move == 'U')
                y++;
            else if(move == 'D')
                y--;
            else if(move == 'L')
                x--;
            else
                x++;
        }
        if(!x && !y)
            return true;
        return false;
    }
};

Welcome to reprint, indicate the source.

Question source: LeetCode
Link: https://leetcode-cn.com/problems/robot-return-to-origin

Guess you like

Origin blog.csdn.net/qq_36583373/article/details/108277357