Leetcode 657. Robot Return to Origin
The problem is taken from LeetCode:
There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves represented by a string, return true
if the robot returns to the origin after completing all of its moves, or false
otherwise.
The input string moves contains characters that represent the robot’s movement:
'U'
(Up)'D'
(Down)'R'
(Right)'L'
(Left)The robot makes one move per character in the string.
moves
can range from 1 to 10,000.'U'
, 'D'
, 'L'
, and 'R'
.To determine if the robot ends up at the origin (0, 0)
after executing all moves, consider the net effect of each type of move:
'U'
(Up) increases the y-coordinate by 1.'D'
(Down) decreases the y-coordinate by 1.'R'
(Right) increases the x-coordinate by 1.'L'
(Left) decreases the x-coordinate by 1.To solve the problem:
(x, y)
to (0, 0)
.moves
string and adjust the coordinates based on the type of move.(x, y)
is (0, 0)
.If (x, y)
is (0, 0)
, return true
. Otherwise, return false
.
moves
string, as we iterate through the string once.Here is the C++ implementation of the solution:
#include <string>
using namespace std;
class Solution {
public:
bool judgeCircle(string moves) {
int x = 0, y = 0;
for (char move : moves) {
if (move == 'U') {
y++;
} else if (move == 'D') {
y--;
} else if (move == 'R') {
x++;
} else if (move == 'L') {
x--;
}
}
return (x == 0) && (y == 0);
}
};
This code solves the problem by simply iterating through the moves
string, updating the x and y coordinates, and finally checking if the coordinates return to the origin.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?