0%

1041. Robot Bounded In Circle

O(n) time
判断是否能在一个circle里:

  1. 跑一遍所有instructions之后能回到原点
  2. 即使不能回到原点,但是最后的方向跟初始不一样(只要方向不一样,跑两遍或者四遍还是回到原点)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isRobotBounded(string instructions) {
int x = 0, y = 0, i = 0, dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}; // 方向顺序NESW
for (char c : instructions) {
switch (c) {
case 'L': i = (i + 3) % 4; break; // 左拐等于右拐三次
case 'R': i = (i + 1) % 4; break;
default: x += dx[i]; y += dy[i]; break;
}
}
return x == 0 && y == 0 || i > 0;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool isRobotBounded(string instructions) {
int x = 0, y = 0, d = 0, dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
for (int i = 0; i < 4; ++i) {
if (isBounded(x, y, d, dx, dy, instructions)) return true;
}
return false;
}

bool isBounded(int &x, int &y, int &d, int dx[], int dy[], const string &ins) {
for (char c : ins) {
switch (c) {
case 'L': d = (d + 3) % 4; break;
case 'R': d = (d + 1) % 4; break;
default: x += dx[d]; y += dy[d]; break;
}
}
return x == 0 && y == 0;
}
};