每日一题(set集合)-874. 模拟行走机器人

题目

874. 模拟行走机器人

题解思路

  • 初始方向朝y轴正方向,遇到指令command == -1 则向右转, 若为 -2 则向左转

  1. 定义方向[-1,0]、[0,1]、[1,0]、[0,-1] 分别为朝x轴负方向, y轴正方向, x轴正方向,y轴负方向
  2. 初始方向为[0,1], 若向右转 则方向变为[-1,0]、若向左转方向变为[1,0]。
  3. 若向右转则不断 向右递加, 向左转则向左递减
  4. 同时建立集合set 存储有障碍的点。(set集合查询时间复杂度为o(1))

代码

C++

class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        int dirs[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
        int sx = 0, sy = 0, res = 0, d = 1;
        set<pair<int, int>> mp;
        for(int i = 0; i < obstacles.size(); ++i){
            pair<int, int> t(obstacles[i][0], obstacles[i][1]);
            mp.insert(t);
        }
        for (int c : commands){
            if (c < 0){
                d += c == -1 ? 1 : -1;
                d %= 4;
                if (d < 0){
                    d += 4;
                }
            }else{
                for (int i = 0; i < c; ++i){
                    int nx = sx + dirs[d][0];
                    int ny = sy + dirs[d][1];
                    pair<int, int> t(nx, ny);
                    if (mp.count(t)){
                        break;
                    }
                    res = max(res, nx * nx + ny * ny);
                    sx = nx;
                    sy = ny;
                }
            }
            
        } 
        return res;
    }
};

Python

class Solution:
    def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
        dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]]
        sx, sy = 0, 0
        d = 1
        res = 0
        mp = set([tuple(i) for i in obstacles])
        for c in commands:
            if c < 0:
                d += 1 if c == -1 else -1
                d %= 4
            else:
                for i in range(c):
                    if tuple([sx + dirs[d][0], sy + dirs[d][1]]) in mp:
                        break
                    else:
                        sx += dirs[d][0]
                        sy += dirs[d][1]
                        res = max(res, sx*sx + sy * sy)
        return res 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值