题目链接:1041. 困于环中的机器人
方法:模拟
解题思路
模拟机器人的行动过程,若再重复四轮之后仍没有回到起始状态,则机器人可以离开,否则不能离开。
代码
class Solution {
public:
bool isRobotBounded(string instructions) {
int mov[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int x = 0, y = 0, cnt = 0, direct = 0; // 0-北,1-东,2-南,3-西
while (cnt < 4) {
for (auto &c : instructions) {
if (c == 'L') direct = (direct + 3) % 4;
else if (c == 'R') direct = (direct + 1) % 4;
else {
x += mov[direct][0];
y += mov[direct][1];
}
}
if (x == 0 && y == 0 && direct == 0) return true;
cnt ++ ;
}
return false;
}
};
复杂度分析
时间复杂度:\(O(n)\);
空间复杂度:\(O(1)\)。