Thursday, December 20, 2018

874. Walking Robot Simulation

Bug -> It is asking to return the maximum distance instead of the final distance...

75.08 %
class Solution {
    private int[] dx = new int[]{0, 1, 0, -1};
private int[] dy = new int[]{1, 0, -1, 0};
public int robotSim(int[] commands, int[][] obstacles) {
// key-y, value-set of x -> for (y,x) that are obstacles
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int[] obstacle : obstacles) {
map.putIfAbsent(obstacle[1], new HashSet<>());
map.get(obstacle[1]).add(obstacle[0]);
}
// pointer of direction
int[] curr = new int[]{0, 0};
int pd = 0;
for (int command : commands) {
if (command == -2) { // turn left
pd = (pd + 3) % 4;
} else if (command == -1) {
pd = (pd + 1) % 4;
} else {
while (command-- > 0) {
int[] next = new int[]{curr[0] + dy[pd], curr[1] + dx[pd]};
if (map.containsKey(next[0]) && map.get(next[0]).contains(next[1])) {
break;
} else {
                        curr = next;
                    }
}
}
}
return (int)(Math.pow(curr[0], 2) + Math.pow(curr[1], 2));
}
}

No comments:

Post a Comment