This is my 37th day of participating in the First Challenge 2022

preface

  • Some love each other, some drive at night to watch the sea, someleetcodeYou can’t do the first one, so you can see,leetcodeThe problem has weight. Today we’re going to meet them

Title address

Can the robot return to the origin

Topic describes

In two dimensions, I have a robot that starts at the origin (0, 0). Give the order of its movement and determine whether the robot ends at (0, 0) after it completes its movement.

The order of moves is indicated by the string moves. The character move[I] indicates its i-th move. The effective actions of the robot are R (right), L (left), U (up) and D (down).

Returns true if the robot returns to the origin after completing all actions. Otherwise, return false.

Note: It doesn’t matter which way the robot is “facing”. “R” will always make the robot move to the right once, “L” will always move to the left, etc. Furthermore, assume that the robot moves by the same amount each time it moves.

 

Example 1:

Enter: moves = "UD" Output: true Explanation: The robot moves up once, then down once. All actions have the same magnitude, so it eventually returns to where it started. Therefore, we return true.Copy the code

Example 2:

Input: moves = "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 does not return to the origin at the end of the move.Copy the code

 

Tip:

1 <= moves. Length <= 2 * 104 Moves only contains characters 'U', 'D', 'L' and 'R'Copy the code

simulation

Train of thought

  • We just need to follow the instructions to simulate the coordinates of the robot’s movement. At the beginning, the coordinate of the robot is (0,0). After traversing all the instructions and moving the robot, it is enough to judge whether the coordinate of the robot is (0,0).

  • Specifically, we use two variables x and y to represent the robot’s current coordinates as (x,y), and x=0 and y=0 at the beginning. Next we iterate over the instructions and update the coordinates of the robot:

  • If the instruction is U, let y=y−1

  • If the instruction is D, let y=y+1

  • If the instruction is L, let x=x−1

  • If the instruction is R, let x=x+1

  • Finally, determine whether (x,y) is (0,0).

solution

/ * * *@param {string} moves
 * @return {boolean}* /
var judgeCircle = function (moves) {
    let x = 0, y = 0;
    for (let i = 0; i < moves.length; i++) {
        if (moves[i] === 'R') x++
        if (moves[i] === 'L') x--
        if (moves[i] === 'U') y--
        if (moves[i] === 'D') y++
    }
    return x === 0 && y === 0
};

Copy the code

Write in the last

  • I hope you find it rewarding