874. 行走机器人模拟

模拟

描述方向时有个技巧:int[][] dx = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
分别存储机器人向上、右、下、左走时,坐标应该如何变换

class Solution {
    public int robotSim(int[] commands, int[][] obstacles) {
        int max = 0;
        int[][] dx = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int k = 0;
        Map<String, Boolean> map = new HashMap<>();
        for (int i = 0; i < obstacles.length; i++) {
            map.put(obstacles[i][0] + "," + obstacles[i][1], true);
        }
        int p = 0, q = 0;
        for (int command : commands) {
            if (command == -1) {
                k = (k + 1) % 4;
            } else if (command == -2) {
                k = (k + 4 - 1) % 4;
            } else {
                int cur[] = dx[k];
                for (int i = 0; i < command; i++) {
                    if (map.containsKey((p + cur[0]) + "," + (q + cur[1]))) {
                        break;
                    }
                    p += cur[0];
                    q += cur[1];
                }
                max = Math.max(max, p * p + q * q);
            }
        }
        return max;
    }
}

相关文章:

  • 2022-12-23
  • 2021-09-09
  • 2022-01-18
  • 2022-01-09
  • 2021-07-18
  • 2021-12-18
  • 2021-12-27
  • 2022-12-23
猜你喜欢
  • 2021-10-07
  • 2021-12-03
  • 2021-11-01
  • 2021-12-14
  • 2022-12-23
  • 2021-12-22
  • 2022-12-23
相关资源
相似解决方案