| 1 | class Solution { |
| 2 | public int robotSim(int[] commands, int[][] obstacles) { |
| 3 | //2,2 -> 2,3 -> 2,4 -> 2,5 -> 2,6 |
| 4 | // 0: North, 1: East, 2: South, 3: West |
| 5 | int[][] directions = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; //constant |
| 6 | int[] curPos = { 0, 0 }; |
| 7 | int res = 0; |
| 8 | int curDir = 0; |
| 9 | HashMap<Integer,HashSet<Integer>> obstacleMap = new HashMap<>(); //O(N) |
| 10 | for (int[] obstacle : obstacles) { //x,y //O(N) |
| 11 | if(!obstacleMap.containsKey(obstacle[0])){ |
| 12 | obstacleMap.put(obstacle[0],new HashSet<>()); |
| 13 | } |
| 14 | obstacleMap.get(obstacle[0]).add(obstacle[1]); |
| 15 | } |
| 16 | |
| 17 | for (int command : commands) { //K |
| 18 | if (command == -1) { |
| 19 | // Turn right |
| 20 | curDir = (curDir + 1) % 4; |
| 21 | continue; |
| 22 | } |
| 23 | if (command == -2) { |
| 24 | // Turn left |
| 25 | curDir = (curDir - 1); |
| 26 | if(curDir==-1){ |
| 27 | curDir=3; |
| 28 | } |
| 29 | continue; |
| 30 | } |
| 31 | |
| 32 | // Move forward |
| 33 | int[] direction = directions[curDir]; |
| 34 | for (int step = 0; step < command; step++) { //9 |
| 35 | int nextX = curPos[0] + direction[0]; |
| 36 | int nextY = curPos[1] + direction[1]; |
| 37 | if(obstacleMap.containsKey(nextX) && obstacleMap.get(nextX).contains(nextY)){ |
| 38 | break; |
| 39 | } |
| 40 | curPos[0] = nextX; |
| 41 | curPos[1] = nextY; |
| 42 | } |
| 43 | |
| 44 | res = Math.max(res,curPos[0] * curPos[0] +curPos[1] * curPos[1]); |
| 45 | } |
| 46 | return res; |
| 47 | } |
| 48 | } |