【Leetcode_easy】874. Walking Robot Simulation

problem

874. Walking Robot Simulation

solution1:

思路:1)如何表示移动的方向以及移动的位置坐标; 2)障碍物坐标如何检查;3)求解的是最大距离;

class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        unordered_set<string> obs;
        for(auto a:obstacles) obs.insert(to_string(a[0]) + "-"+to_string(a[1]));
        //int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        vector<int> dirX = {0, 1, 0, -1};
        vector<int> dirY = {1, 0, -1, 0};
        int res = 0, id = 0, x = 0, y = 0;
        for(auto cmd:commands)
        {
            if(cmd==-1) id = (id+1) % 4;
            else if(cmd==-2) id = (id-1+4) % 4;
            else
            {
                while(cmd-->0 && !obs.count(to_string(x+dirX[id])+"-"+to_string(y+dirY[id])))
                {
                    //cmd--;
                    x += dirX[id];
                    y += dirY[id];
                }
            }
            res = max(res, x*x+y*y);           
        }
        return res;
    }
};

参考

1. Leetcode_easy_874. Walking Robot Simulation;

2. grandyang;

3. discuss;

原文地址:https://www.cnblogs.com/happyamyhope/p/11252142.html