每日一题(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 
相关推荐
小趴蔡ha3 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534783 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
mifengxing4 小时前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
数字化转型分享点滴4 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03014 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比4 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
郝学胜-神的一滴5 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
xrandzj5 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
matlabgoodboy8 小时前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计
用户8356290780518 小时前
Python Word 转 PDF 和 PDF 转 Word 指南
后端·python