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

题目

874. 模拟行走机器人

题解思路

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

  1. 定义方向-1,00,11,00,-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 
相关推荐
骄阳如火4 小时前
Python 性能深度剖析:从“被诟病的慢”到“Rust 重塑”的拐点
python
满怀冰雪4 小时前
03-第一个 Paddle 程序:Tensor 创建、计算与设备管理
人工智能·python·paddle
CClaris5 小时前
大模型量化从0到1(九):用 llama.cpp 把模型转成 GGUF 并跑本地推理
人工智能·pytorch·python·深度学习·llama
学编程的小虎5 小时前
SenseVoice微调
人工智能·python·自然语言处理
c238565 小时前
Bug 猎手入门指南
c++·算法·bug
诸葛说抛光5 小时前
国内大型汽车改装展览会定展 佛山改装 佛山汽车赛事
python·汽车
chouchuang5 小时前
day-030-综合练习-笔记管理器
开发语言·笔记·python
乖巧的妹子6 小时前
Python基础核心知识点详解:内置函数、运算符、字符串方法、数据结构与类型转换
python
幸福清风6 小时前
Python 完美处理Excel合并单元格:拆分填充+自动合并
python·excel·合并单元格·拆分单元格
汤姆小白7 小时前
08-应用部署
人工智能·python·机器学习·numpy·transformer