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
| class Solution { static int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public int robotSim(int[] commands, int[][] obstacles) { Set<Integer> set = new HashSet<>(obstacles.length); for (int[] obstacle : obstacles) { set.add(getIndex(obstacle[0], obstacle[1])); } int ans = 0, k = 0, x = 0, y = 0; for (int command : commands) { if (command == -2) { k = (k + 3) % 4; } else if (command == -1) { k = (k + 1) % 4; } else { while (command-- > 0) { int nx = x + dirs[k][0], ny = y + dirs[k][1]; if (set.contains(getIndex(nx, ny))) break; x = nx; y = ny; ans = Math.max(ans, x * x + y * y); } } } return ans; }
private int getIndex(int x, int y) { return x * 90000 + y; } }
|