LeetCode # 874
Example 1:
Input:
commands = [4,-1,3], obstacles = []
Output:
25
Explanation: The robot starts at (0, 0): 1. Move north 4 units to (0, 4). 2. Turn right. 3. Move east 3 units to (3, 4). The furthest point away from the origin is (3, 4), which is 32 + 42 = 25 units away.
Solution #1 (11ms)
import java.awt.*;
import java.util.HashSet;
import java.util.Set;
class Solution {
int[] xStep = new int[]{0, 1, 0, -1};
int[] yStep = new int[]{1, 0, -1, 0};
int direction = 0, x = 0, y = 0;
int result = 0;
public int robotSim(int[] commands, int[][] obstacles) {
Set<Point> set = new HashSet<>();
for (int[] obs : obstacles) {
set.add(new Point(obs[0], obs[1]));
}
for (int command : commands) {
if (command == -1 || command == -2) {
direction = getDirection(command);
} else {
for (int j = 0; j < command; j++) {
int xTmp = x + xStep[direction];
int yTmp = y + yStep[direction];
Point point = new Point(xTmp, yTmp);
if (set.contains(point)) {
break;
}
x = xTmp;
y = yTmp;
}
}
result = Math.max(result, (x * x) + (y * y));
}
return result;
}
private int getDirection(int d) {
if (d == -2) direction -= 1;
else if (d == -1) direction += 1;
return (direction < 0 ? (direction + 4) : direction) % 4;
}
}
Result #1
More Algorithm!
👇👇
github.com/ggujangi/ggu.leet-code
출처 : leetCode
'LeetCode > Easy' 카테고리의 다른 글
[Java] LeetCode 717 : 1-bit and 2-bit Characters (0) | 2021.04.21 |
---|---|
[Java] LeetCode 953 : Verifying an Alien Dictionary (0) | 2021.04.21 |
[Java] LeetCode 1518 : Water Bottles (0) | 2021.04.17 |
[Java] LeetCode 290 : Word Pattern (0) | 2021.04.17 |
[Java] LeetCode 914 : X of a Kind in a Deck of Cards (0) | 2021.04.17 |