玖月机器人_1041. 困于环中的机器人(Python)

更多精彩内容,请关注【力扣简单题】。

题目

难度:★★☆☆☆

类型:几何、二维数组

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

"G":直走 1 个单位

"L":左转 90 度

"R":右转 90 度

机器人按顺序执行指令 instructions,并一直重复它们。

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

提示

1 <= instructions.length <= 100

instructions[i] 在 {'G', 'L', 'R'} 中

示例

示例 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) -> ... 进行移动。

解答

我们实例化一个机器人类,包含三个方法:向前走一步,左转和右转,包含若干属性:当前位置,当前方向等。根据指令调用即可。

关于回到原点的问题,我们只需要将指令重复4次,因为方向有4个,查看4次之后能否回到原点。

class Robot:

def __init__(self):

self.loc = [0, 0]

self.direction_list = [[0, 1], [-1, 0], [0, -1], [1, 0]] # North, West, South, East

self.direction_id = 0 # North

@property

def cur_direction(self):

return self.direction_list[self.direction_id]

def forward(self):

self.loc = [sum(l) for l in zip(self.loc, self.cur_direction)]

def turn_left(self):

self.direction_id = (self.direction_id + 1) % 4

def turn_right(self):

self.direction_id = (self.direction_id - 1) % 4

class Solution:

def isRobotBounded(self, instructions: str) -> bool:

robot = Robot()

for i in instructions*4:

if i == 'G':

robot.forward()

elif i == 'L':

robot.turn_left()

elif i == 'R':

robot.turn_right()

return robot.loc == [0, 0]

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

你可能感兴趣的:(玖月机器人)