-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path874_walking_robot_simulation.java
78 lines (76 loc) · 2.51 KB
/
874_walking_robot_simulation.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// @lc app=leetcode id=874 lang=java
import java.util.HashSet;
class Solution {
private class Coordinate {
private int x;
private int y;
private char direction;
private int distance;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
this.direction = 'N';
}
public void executeCommand(int steps) {
if (steps == -1) {
switch (direction) {
case 'N': direction = 'E'; break;
case 'E': direction = 'S'; break;
case 'W': direction = 'N'; break;
case 'S': direction = 'W'; break;
}
}
if (steps == -2) {
switch (direction) {
case 'N': direction = 'W'; break;
case 'E': direction = 'N'; break;
case 'W': direction = 'S'; break;
case 'S': direction = 'E'; break;
}
}
int prevX;
int prevY;
while (steps > 0) {
prevX = x;
prevY = y;
switch (direction) {
case 'N': y++; break;
case 'E': x++; break;
case 'W': x--; break;
case 'S': y--; break;
}
if (obstaclesSet.contains(this)) {
x = prevX;
y = prevY;
break;
}
distance = Math.max(distance, x * x + y * y);
steps--;
}
}
public int furthestDistance() {
return distance;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Coordinate)) return false;
Coordinate coordinate = (Coordinate) obj;
return this.x == coordinate.x && this.y == coordinate.y;
}
@Override
public int hashCode() {
return 10 * x + y;
}
}
private HashSet<Coordinate> obstaclesSet = new HashSet<>();
public int robotSim(int[] commands, int[][] obstaclesArr) {
for (int[] obstacle : obstaclesArr)
obstaclesSet.add(new Coordinate(obstacle[0], obstacle[1]));
Coordinate robot = new Coordinate(0, 0);
for (int command : commands) {
robot.executeCommand(command);
}
return robot.furthestDistance();
}
}