Leetcode题874、模拟行走机器人(Python题解)

    科技2024-12-11  27

    问题:

    题目来源:力扣(LeetCode)

    leetcode874.模拟行走机器人

    难度:简单

    分析: 逻辑模拟。 几个小技巧: 1、list是顺序查找,set是哈希查找,所以set会很快。set实际上是一个没有value的字典,因此set的值要求唯一并且是不可变类型。 2、逻辑模拟按照逻辑走就可以,找好状态以及状态转换方式。状态空间的寻找很重要。

    本题中有4个状态,分别面向上、下、左、右,对应4个操作,x方向前进,y方向前进,左转、右转。每个状态对应的操作结果不同,因此每次需要根据前置状态做出判断,提前写个字典对应好各操作带来的变化。

    解决方法: 1:逻辑模拟

    #逻辑模拟 #set是哈希查找,list是顺序查找,所以存成set比较快 #不要直接用dir,python有自己的dir函数,虽然用了也不会出错。 class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: # 字典存储某个方向(key)对应的 [x方向移动,y方向移动,当前方向的左侧,当前方向的右侧] (val) direction = {'up': [0, 1, 'left', 'right'], 'down': [0, -1, 'right', 'left'], 'left': [-1, 0, 'down', 'up'], 'right': [1, 0, 'up', 'down']} x, y = 0, 0 direct = 'up' res = 0 obstacles = set(map(tuple, obstacles)) for command in commands: if command > 0: # 正数的话进行模型行进操作 for step in range(command): if (x + direction[direct][0], y + direction[direct][1]) not in obstacles: x += direction[direct][0] y += direction[direct][1] res = max(res, x ** 2 + y ** 2) else: break else: # 负数的话只改变行进方向 if command == -1: # 右转 direct = direction[direct][3] else: # 即command == -2,左转 direct = direction[direct][2] return res
    Processed: 0.011, SQL: 8