Leetcode 874. Walking Robot Simulation

本文详细解析了LeetCode上的一道题目——行走机器人模拟。通过使用C++实现,文章介绍了如何设计一个算法来模拟机器人在二维平面上的行走,同时避免碰撞到障碍物。算法考虑了方向变化和最大距离计算,利用集合存储障碍物位置,确保机器人不会进入障碍区域。通过遍历指令集,机器人可以改变方向或向前移动,同时更新最大距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章作者:Tyan
博客:noahsnail.com  |  优快云  |  简书

1. Description

Walking Robot Simulation

2. Solution

class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        int x = 0;
        int y = 0;
        int maximum = 0;
        char directions[] = {'N', 'E', 'S', 'W'};
        int index = 0;
        set<pair<int, int>> obstacleSet;
        for (vector<int> obstacle: obstacles) {
            obstacleSet.insert(make_pair(obstacle[0], obstacle[1]));
        }
        for(int i = 0; i < commands.size(); i++) {
        	if(commands[i] == -1) {
        		index = (index + 1) % 4;
        	}
        	else if(commands[i] == -2) {
        		index = (index - 1 + 4) % 4;
        	}
        	else {
        		for(int j = 0; j < commands[i]; j++) {
        			moveForward(obstacleSet, x, y, directions[index]);
        			maximum = max(maximum, x*x + y*y);
        		}
        	}
        }
        return maximum;
    }


private:
	void moveForward(set<pair<int, int>>& obstacleSet, int& x, int& y, char direction) {
		switch(direction) {
			case 'N':
				if (obstacleSet.find(make_pair(x, y + 1)) == obstacleSet.end()) {
                    y += 1;
                }
				break;
			case 'E':
				if (obstacleSet.find(make_pair(x + 1, y)) == obstacleSet.end()) {
                    x += 1;
                }
				break;
			case 'S':
				if (obstacleSet.find(make_pair(x, y - 1)) == obstacleSet.end()) {
                    y -= 1;
                }
				break;
			case 'W':
				if (obstacleSet.find(make_pair(x - 1, y)) == obstacleSet.end()) {
                    x -= 1;
                }
				break;
		}
	}
};

Reference

  1. https://leetcode.com/problems/walking-robot-simulation/description/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值