874. Walking Robot Simulation

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands:
这里写图片描述
对于一个机器人,给出它的行驶方向和距离,计算它距离起点的最大距离。

2,题目思路
对于这道题,需要注意的是这个距离是最大的距离,而不是机器人到达终点之后到起点的距离,因此需要每执行一步就计算一次距离的最大值。
另外,还值得注意的是,pair不能作为unorder_set的参数。

3,程序源码

static int pr = []() { 
    std::ios::sync_with_stdio(false); 
    cin.tie(NULL);  
    return 0; 
}();

class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        set<pair<int, int>> obs;
        vector<vector<int>> dir {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
        int d = 0, res = 0, x = 0, y = 0;
        for(auto o : obstacles)
            obs.insert(make_pair(o[0], o[1]));
        for(auto c :commands)
        {
            if(c == -2)
                d = (d + 1) % 4;
            else if(c == -1)
                d = (d - 1 + 4) % 4;
            else
                while(c-- && obs.find(make_pair(x+dir[d][0], y+dir[d][1])) == obs.end())
                {
                    x +=dir[d][0];
                    y +=dir[d][1];
                }
            res = max(res, x*x+y*y);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值