题目地址:
https://leetcode.com/problems/robot-bounded-in-circle/
有个平面直角坐标系里的机器人,从
(
0
,
0
)
(0,0)
(0,0)出发,一开始面向北。给定一个长
n
n
n的字符串
s
s
s,其只含三种字母'G', 'L', 'R'
,'G'
代表前进,后面两个字母分别代表左转和右转。问
s
s
s这个命令无限次执行的情况下,机器人的路径是否是有界的。
我们证明,路径有界当且仅当其执行完 s s s回到原点,或者执行完 s s s后朝向不是北方。
充分性:
考虑
s
s
s执行完后的位移向量
x
⃗
=
(
a
,
b
)
\vec{x}=(a,b)
x=(a,b),如果
∣
x
⃗
∣
=
0
|\vec{x}|=0
∣x∣=0,那么无论其面对哪个方向,再执行一遍
s
s
s,由旋转对称性,其依然会回到原点,所以有界。如果
∣
x
⃗
∣
>
0
|\vec{x}|> 0
∣x∣>0,但方向不是朝北了,如果方向是朝南,那么由旋转对称性,再执行
1
1
1遍会回到原点。如果方向是朝东或者朝西,那么再执行
3
3
3遍就会回到原点(会绕出一个正方形)。所以是有界的。
必要性:
反证法,如果执行完
s
s
s后不在原点并且面向北方,那么再执行若干次后位置将会是
n
x
⃗
n\vec{x}
nx,这是无界的。
代码如下:
import java.util.Map;
public class Solution {
public boolean isRobotBounded(String instructions) {
int x = 0, y = 0, dir = 0;
// 0,1,2,3分别对应北,东,南,西四个方向
Map<Integer, int[]> map = Map.of(
0, new int[]{0, 1},
1, new int[]{1, 0},
2, new int[]{0, -1},
3, new int[]{-1, 0});
for (int i = 0; i < instructions.length(); i++) {
char ch = instructions.charAt(i);
switch (ch) {
case 'G':
int[] d = map.get(dir);
x += d[0];
y += d[1];
break;
case 'R':
dir = (dir + 1) % 4;
break;
case 'L':
dir = (dir + 3) % 4;
break;
}
}
return dir != 0 || (x == 0 && y == 0);
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。