每日一题(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 
相关推荐
音视频牛哥14 分钟前
C++20之2025年上桌我坐哪儿?
c++·编程语言·ai 编程
红队it16 分钟前
【数据分析大屏】基于Django+Vue汽车销售数据分析可视化大屏(完整系统源码+数据库+开发笔记+详细部署教程+虚拟机分布式启动教程)✅
python·数据分析·spark·汽车·大屏端
蹦蹦跳跳真可爱58924 分钟前
Python----计算机视觉处理(opencv:图片灰度化)
人工智能·python·opencv·计算机视觉
香菇滑稽之谈1 小时前
代理模式的C++实现示例
c++·设计模式·系统安全·代理模式
Dante7981 小时前
【数据结构】二叉搜索树、平衡搜索树、红黑树
数据结构·c++·算法
HelloGitHub1 小时前
经过 10 亿级性能验证的隐私计算开源利器
python·开源·github
一号言安1 小时前
牛客python蓝桥杯11-32(自用)
开发语言·python
梦丶晓羽1 小时前
自然语言处理:主题模型
人工智能·python·自然语言处理·lda·主题模型
weixin_525936332 小时前
Python数据分析之机器学习基础
python·机器学习·数据分析
奕天者2 小时前
C++学习笔记(十七)——类之封装
c++·笔记·学习