-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsolution.java
More file actions
50 lines (41 loc) · 1.39 KB
/
solution.java
File metadata and controls
50 lines (41 loc) · 1.39 KB
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
43
44
45
46
47
48
49
50
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
// Store obstacles in a HashSet
Set<String> obstacleSet = new HashSet<>();
for (int[] obs : obstacles) {
obstacleSet.add(obs[0] + "," + obs[1]);
}
// Directions: North, East, South, West
int[] dx = { 0, 1, 0, -1 };
int[] dy = { 1, 0, -1, 0 };
int dir = 0; // North
int x = 0, y = 0;
int maxDistance = 0;
for (int command : commands) {
// Turn right
if (command == -1) {
dir = (dir + 1) % 4;
}
// Turn left
else if (command == -2) {
dir = (dir + 3) % 4;
}
// Move forward
else {
for (int step = 0; step < command; step++) {
int nextX = x + dx[dir];
int nextY = y + dy[dir];
String nextPos = nextX + "," + nextY;
// Stop if obstacle exists
if (obstacleSet.contains(nextPos)) {
break;
}
x = nextX;
y = nextY;
maxDistance = Math.max(maxDistance, x * x + y * y);
}
}
}
return maxDistance;
}
}