1041. 困于环中的机器人(Python)

2021-07-05  本文已影响0人  玖月晴

难度:★★★☆☆
类型:数组
方法:模拟

题目

力扣链接请移步本题传送门
更多力扣中等题的解决方案请移步力扣中等题目录

在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方。机器人可以接受下列三条指令之一:

"G":直走 1 个单位
"L":左转 90 度
"R":右转 90 度
机器人按顺序执行指令 instructions,并一直重复它们。

只有在平面中存在环使得机器人永远无法离开时,返回 true。否则,返回 false。

示例 1:

输入:"GGLLGG"
输出:true
解释:
机器人从 (0,0) 移动到 (0,2),转 180 度,然后回到 (0,0)。
重复这些指令,机器人将保持在以原点为中心,2 为半径的环中进行移动。

示例 2:

输入:"GG"
输出:false
解释:
机器人无限向北移动。

示例 3:

输入:"GL"
输出:true
解释:
机器人按 (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... 进行移动。

提示:

1 <= instructions.length <= 100
instructions[i] 在 {'G', 'L', 'R'} 中

解答

我们可以按部就班的模拟,如果机器人在执行指令后能够回到原来位置,则说明被困在环里。

注意事项:

第一,变量约定:location为机器人当前位置,direction为机器人当前方向,都是两个元素的向量。

第二,坐标约定:北方为(1,0),采用笛卡尔坐标系,初始位置(0,0)

第三,旋转的实现。矩阵的本质是旋转,方向的旋转通过方向向量乘以旋转矩阵实现。

左转的旋转矩阵:

[[0,1],
 [-1,0]]

右转的旋转矩阵:

[[0,-1],
 [1,0]]

第四,对于“GL”这类用例,我们需要将它重复四次,才能验证是否被困在环中。

class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        instructions *= 4
        def rotate(direction, matrix):      # 向量乘以矩阵实现方向旋转
            x, y = direction
            (m00, m01), (m10, m11) = matrix[0], matrix[1]
            return x * m00 + y * m10, x * m01 + y * m11

        def next(location, direction, instruct):
            x, y = location
            dx, dy = direction

            if instruct == "G":
                return (x + dx, y + dy), direction
            elif instruct == "L":
                direction = rotate(direction, [[0, 1],
                                               [-1, 0]])
                return location, direction
            elif instruct == "R":
                direction = rotate(direction, [[0, -1],
                                               [1, 0]])
                return location, direction
            else:
                raise Exception

        start = location = (0, 0)
        direction = (1, 0)
        for instruct in instructions:
            location, direction = next(location, direction, instruct)
        return location == start


s = Solution()
print(s.isRobotBounded("GL"))

如有疑问或建议,欢迎评论区留言~

有关更多力扣中等题的python解决方案,请移步力扣中等题解析

上一篇下一篇

猜你喜欢

热点阅读