-
Notifications
You must be signed in to change notification settings - Fork 0
/
874. Walking Robot Simulation
33 lines (32 loc) · 1.06 KB
/
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
import java.util.HashSet;
import java.util.Set;
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int x = 0, y = 0, d = 0;
int[][] direction = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
int maxDistance = 0;
Set<String> obstacleSet = new HashSet<>();
for (int[] obstacle : obstacles) {
obstacleSet.add(obstacle[0] + "," + obstacle[1]);
}
for (int cmd : commands) {
if (cmd == -1) {
d = (d + 1) % 4;
} else if (cmd == -2) {
d = (d + 3) % 4;
} else {
for (int i = 0; i < cmd; i++) {
int nx = x + direction[d][0];
int ny = y + direction[d][1];
if (obstacleSet.contains(nx + "," + ny)) {
break;
}
x = nx;
y = ny;
maxDistance = Math.max(maxDistance, x * x + y * y);
}
}
}
return maxDistance;
}
}