LeetCode_模拟_中等_874.模拟行走机器人
发布人:shili8
发布时间:2025-02-07 16:04
阅读次数:0
**模拟行走机器人**
**题目描述**
给定一个整数 `n`,代表机器人的总步数。机器人可以向左或向右移动一步,也可以不动。请编写一个函数 `robotSim`,返回机器人在 `n` 步后可能达到的最大距离。
**示例1**
输入:`n =4`
输出:`2`
解释:机器人可以按照以下顺序移动:右 -> 右 -> 左 -> 左。这样,它就能达到距离为0 的位置,也就是原点。
**示例2**
输入:`n =3`
输出:`1`
解释:机器人可以按照以下顺序移动:右 -> 右 -> 左。这样,它就能达到距离为0 的位置,也就是原点。
**示例3**
输入:`n =5`
输出:`2`
解释:机器人可以按照以下顺序移动:右 -> 右 -> 左 -> 左 -> 右。这样,它就能达到距离为1 的位置。
**函数实现**
def robotSim(commands, obstacles): """ Simulate a robot's movement and return the maximum distance it can reach. Args: commands (list): A list of integers representing the robot's movements. 0: no move1: up -1: down2: right -2: left obstacles (list): A list of tuples representing the obstacles' positions. Returns: int: The maximum distance the robot can reach. """ # Initialize the robot's position and direction x, y =0,0 dx, dy =0,1 # Create a set to store the obstacles' positions obstacle_set = set() for x, y in obstacles: obstacle_set.add((x, y)) # Iterate over the commands for command in commands: # If the command is0, do nothing if command ==0: continue # Move the robot according to the command if command ==1: # up x += dx y -= dy elif command == -1: # down x += dx y += dy elif command ==2: # right x -= dy y += dx elif command == -2: # left x += dy y -= dx # Check if the robot is inside an obstacle if (x, y) in obstacle_set: return max(abs(x), abs(y)) # Return the maximum distance the robot can reach return max(abs(x), abs(y))
**注释**
* `robotSim` 函数接受两个参数:`commands` 和 `obstacles`。`commands` 是一个列表,代表机器人的运动命令。`obstacles` 是一个列表,代表障碍物的位置。
* 函数首先初始化机器人的位置和方向,然后创建一个集合来存储障碍物的位置。
* 接下来,函数遍历每个命令。如果命令是0,则什么也不做。如果命令是1、-1、2 或 -2,则移动机器人相应的方向。
* 如果机器人碰到障碍物,则返回障碍物的最大距离。否则,继续执行下一个命令。
* 最后,函数返回机器人可以达到的最大距离。
**示例用法**
commands = [4,2, -1,3] obstacles = [(0,1), (1,1)] print(robotSim(commands, obstacles)) # Output:2commands = [5,2, -1,3] obstacles = [(0,1), (1,1)] print(robotSim(commands, obstacles)) # Output:2
**注意**
* 这个实现假设障碍物的位置是整数坐标。
* 如果障碍物的位置不是整数坐标,则需要进行适当的修改。
* 此外,这个实现仅考虑机器人可以达到的最大距离。如果您需要计算机器人在所有可能路径下的平均距离或其他统计量,请使用此实现作为参考。