1. public class Solution {
    2. public int robotSim(int[] commands, int[][] obstacles) {
    3. //定一个set,存储障碍物。把障碍物的XY坐标用String拼接保存即可
    4. HashSet<String> set = new HashSet<>();
    5. for(int i = 0;i < obstacles.length;i++){
    6. set.add(obstacles[i][0] + "_" + obstacles[i][1]);
    7. }
    8. //制定一个方向dir
    9. //北:0,东:1,南:2,西:3
    10. //这样就可以得出
    11. // 右转 = (dir + 1) % 4
    12. // 左转 = (dir -1 + 4) % 4 = (dir + 3) %4
    13. int dir = 0;
    14. //结合方向数组,制定X,Y的行进数组
    15. // 北,东,南,西
    16. int[] dx = {0,1,0,-1};
    17. int[] dy = {1,0,-1,0};
    18. //初始坐标x,y = 0在原点
    19. int x = 0;
    20. int y = 0;
    21. //初始化返回值为0
    22. int res = 0;
    23. for(int i : commands){
    24. if(i == -2){
    25. //左转
    26. dir = (dir + 3) % 4;
    27. }else if(i == -1){
    28. //右转
    29. dir = (dir + 1) % 4;
    30. }else{
    31. //行进
    32. for(int step = 0;step < i;step++){
    33. //下一个坐标是
    34. int nextX = x + dx[dir];
    35. int nextY = y + dy[dir];
    36. //判断是不是障碍物,如果存在set,则此次行进终止,执行下一个操作,否则xy行进
    37. if(set.contains(nextX + "_" + nextY)){
    38. break;
    39. }else {
    40. x = nextX;
    41. y = nextY;
    42. }
    43. }
    44. //行进完成后比对最远距离
    45. res = Math.max(res, x*x + y*y);
    46. }
    47. }
    48. return res;
    49. }
    50. }