1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00

java: add «874. Walking Robot Simulation»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-04 21:43:13 +02:00
parent 4d20c963ba
commit 92e7ac3d19
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,57 @@
import java.util.HashSet;
class Solution {
private static final int TURN_LEFT = -2;
private static final int TURN_RIGHT = -1;
private record Vec(int x, int y) {
public Vec turnLeft() {
return new Vec(-y, x);
}
public Vec turnRight() {
return new Vec(y, -x);
}
public Vec add(Vec other) {
return new Vec(x + other.x, y + other.y);
}
public int distance() {
return Math.abs(x * x + y * y);
}
}
public int robotSim(int[] commands, int[][] obstacles) {
int maxDistance = 0;
// Process obstacles
var uniqueObstacles = new HashSet<Vec>();
for (int[] obstacle : obstacles) {
uniqueObstacles.add(new Vec(obstacle[0], obstacle[1]));
}
var pos = new Vec(0, 0);
var direction = new Vec(0, 1);
for (int command : commands) {
if (command == TURN_LEFT) {
direction = direction.turnLeft();
} else if (command == TURN_RIGHT) {
direction = direction.turnRight();
}
for (var steps = 0; steps < command; ++steps) {
var next = pos.add(direction);
if (uniqueObstacles.contains(next)) {
break;
}
pos = next;
maxDistance = Math.max(maxDistance, pos.distance());
}
}
return maxDistance;
}
}