Judge Route Circle
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
Example 1: Input: "UD" Output: true Example 2: Input: "LL" Output: false
Solution 1
bool judgeCircle(string moves) {
int x = 0;
int y = 0;
for (auto move: moves) {
switch (move) {
case 'U':
y += 1;
break;
case 'D':
y -= 1;
break;
case 'L':
x -= 1;
break;
case 'R':
x += 1;
default:
continue;
}
}
return x == 0 && y == 0;
}
Solution: Using Pair
bool judgeCircle(string moves) {
pair<int, int> pos;
unordered_map<char, pair<int, int>> m;
m['U'] = make_pair(0, 1);
m['D'] = make_pair(0, -1);
m['L'] = make_pair(-1, 0);
m['R'] = make_pair(1, 0);
for (auto move: moves) {
pos.first += m[move].first;
pos.second += m[move].second;
}
return pos == make_pair(0, 0);
}