LC.P874[模拟行走机器人]

方法一:哈希表+模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {

static int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

public int robotSim(int[] commands, int[][] obstacles) {
Set<Integer> set = new HashSet<>(obstacles.length);
for (int[] obstacle : obstacles) {
set.add(getIndex(obstacle[0], obstacle[1]));
}
int ans = 0, k = 0, x = 0, y = 0;
for (int command : commands) {
if (command == -2) {
// 左转
k = (k + 3) % 4;
} else if (command == -1) {
// 右转
k = (k + 1) % 4;
} else {
// 直行
while (command-- > 0) {
int nx = x + dirs[k][0], ny = y + dirs[k][1];
if (set.contains(getIndex(nx, ny))) break;
x = nx;
y = ny;
ans = Math.max(ans, x * x + y * y);
}
}
}
return ans;
}

private int getIndex(int x, int y) {
return x * 90000 + y;
}
}
  • 时间复杂度:$O(n \times C + m)$,$C$为每次可移动的最大步数,最大为$9$,$n$和$m$分别为$commands$和$obstacles$的长度
  • 空间复杂度:$O(m)$