[leetcode] 874. 行走機器人模擬(周賽)


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;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM