每日一题(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 
相关推荐
蓝婷儿1 分钟前
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
开发语言·python·学习
chao_78927 分钟前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
南岩亦凛汀1 小时前
在Linux下使用wxWidgets进行跨平台GUI开发
c++·跨平台·gui·开源框架·工程实战教程
大霞上仙1 小时前
nonlocal 与global关键字
开发语言·python
曦月逸霜1 小时前
第34次CCF-CSP认证真题解析(目标300分做法)
数据结构·c++·算法
galaxy_strive1 小时前
绘制饼图详细过程
开发语言·c++·qt
Mark_Aussie2 小时前
Flask-SQLAlchemy使用小结
python·flask
程序员阿龙2 小时前
【精选】计算机毕业设计Python Flask海口天气数据分析可视化系统 气象数据采集处理 天气趋势图表展示 数据可视化平台源码+论文+PPT+讲解
python·flask·课程设计·数据可视化系统·天气数据分析·海口气象数据·pandas 数据处理
ZHOU_WUYI2 小时前
Flask与Celery 项目应用(shared_task使用)
后端·python·flask
且慢.5892 小时前
Python_day47
python·深度学习·计算机视觉