用 Python 编写程序检查机器人是否能到达目标位置
pythonserver side programmingprogramming更新于 2026/1/12 23:40:17
假设我们有一个机器人,它当前位于位置 (0, 0)(笛卡尔平面)。如果我们有一个它可以进行的动作列表,其中包含 N(北)、S(南)、W(西)和 E(东)。我们必须检查它是否可以到达目的地坐标(x,y)。
因此,如果输入为 moves = ['N','N','E','E','S'], (x,y) = (2,1),则输出将为 True,

为了解决这个问题,我们将遵循以下步骤 −
- temp_coord := [0,0]
- 对于 moves 中的每个移动,执行
- 如果移动与"N",则
- temp_coord[1] := temp_coord[1] + 1
- 否则,当 move 与 "S" 相同时,则
- temp_coord[1] := temp_coord[1] - 1
- 否则,当 move 与 "E" 相同时,则
- temp_coord[0] := temp_coord[0] + 1
- 否则,当 move 与 "W" 相同时,则
- temp_coord[0] := temp_coord[0] - 1
- 如果移动与"N",则
- 当 temp_coord[0] 与 coord[0] 相同且 temp_coord[1] 与 coord[1] 相同时返回 True,否则返回 false。
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, moves, coord): temp_coord = [0,0] for move in moves: if move == "N": temp_coord[1] += 1 elif move == "S": temp_coord[1] -= 1 elif move == "E": temp_coord[0] += 1 elif move == "W": temp_coord[0] -= 1 return temp_coord[0] == coord[0] and temp_coord[1] == coord[1] ob = Solution() moves = ['N','N','E','E','S'] coord = [2,1] print(ob.solve(moves, coord))
输入
['N','N','E','E','S'], [2,1]
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

