874. Walking Robot Simulation

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
36
37
38
39
40
41
42
class Solution {

private static final int[][] DIRECTIONS = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 上,右,下,左

public int robotSim(int[] commands, int[][] obstacles) {
int maxDistanceSquare = 0;

Map<Integer, Set<Integer>> obstacleMap = new HashMap<>();
for (int[] obstacle : obstacles) {
obstacleMap.computeIfAbsent(obstacle[0], key -> new HashSet<>()).add(obstacle[1]);
}

int i = 0, j = 0;
int directionIndex = 0; // 初始化方向为上
for (int command : commands) {
if (command == -2) {
// 左转
directionIndex = (directionIndex - 1 + DIRECTIONS.length) % DIRECTIONS.length;
} else if (command == -1) {
// 右转
directionIndex = (directionIndex + 1) % DIRECTIONS.length;
} else {
// 向前移动
int[] direction = DIRECTIONS[directionIndex];
for (int k = 0; k < command; k++) {
int nextI = i + direction[0];
int nextJ = j + direction[1];
if (obstacleMap.getOrDefault(nextI, Collections.emptySet()).contains(nextJ)) {
break;
} else {
i = nextI;
j = nextJ;
maxDistanceSquare = Math.max(maxDistanceSquare, i * i + j * j);
}
}
}
}

return maxDistanceSquare;
}

}

References

874. Walking Robot Simulation