leetcode 874. Walking Robot Simulation

874. Walking Robot Simulation

https://www.cnblogs.com/grandyang/p/10800993.html

每走一步(不是没走commands里的一个数字)计算到原点的距离,每走一步都可能遇到障碍物,需要将障碍物的坐标进行存储,以判断是否停止行走。

左转90度,右转90度转换成在x、y的坐标变换上来。左转前进一个index,右转前进一个index,对4取余确保不越界

不知道为什么用unordered_set就编译出错。

class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        int x = 0,y = 0,res = 0,index = 0;
        set<pair<int,int> > s;
        for(int i = 0;i < obstacles.size();i++)
            s.insert({obstacles[i][0],obstacles[i][1]});
        vector<int> x_move{0,1,0,-1},y_move{1,0,-1,0};
        for(int command : commands){
            if(command == -1)
                index = (index + 1)%4;
            else if(command == -2)
                index = (index - 1 + 4)%4;
            else{
                while(command-- > 0 && !s.count(make_pair(x + x_move[index],y + y_move[index]))){
                    x += x_move[index];
                    y += y_move[index];
                }
            }
            res = max(res,x*x + y*y);    
        }
        return res;
    }
};

 

posted @ 2019-05-09 21:54  有梦就要去实现他  阅读(230)  评论(0编辑  收藏  举报