每日一题(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++

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

c 复制代码
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 
相关推荐
2401_841495641 分钟前
【语音识别】混合高斯模型
人工智能·python·算法·机器学习·语音识别·gmm·混合高斯模型
利刃大大11 分钟前
【高并发服务器】十二、LoopThreadPool线程池管理模块
服务器·c++·项目
Summer_Uncle25 分钟前
【C++学习】对象特性--继承
开发语言·c++·学习
徐凤年lll1 小时前
python 初学2
开发语言·python
艾莉丝努力练剑2 小时前
【Git:基本操作】深度解析Git:从初始Git到熟悉基本操作
大数据·linux·c++·人工智能·git·gitee·指令
坚持就完事了2 小时前
解析数据练习(小项目)
python
周周记笔记2 小时前
Pycharm详解:高效Python开发的首选IDE
ide·python·pycharm
香辣西红柿炒蛋2 小时前
Python企业编码规范
python
CN-Dust2 小时前
【C++】2025CSP-J第二轮真题及解析
开发语言·c++·算法
夏鹏今天学习了吗2 小时前
【LeetCode热题100(57/100)】括号生成
算法·leetcode·职场和发展