更多精彩內(nèi)容桑孩,請關(guān)注【力扣簡單題】拜鹤。
題目
難度:★★☆☆☆
類型:幾何、二維數(shù)組
在無限的平面上流椒,機(jī)器人最初位于 (0, 0) 處敏簿,面朝北方。機(jī)器人可以接受下列三條指令之一:
"G":直走 1 個單位
"L":左轉(zhuǎn) 90 度
"R":右轉(zhuǎn) 90 度
機(jī)器人按順序執(zhí)行指令 instructions宣虾,并一直重復(fù)它們惯裕。
只有在平面中存在環(huán)使得機(jī)器人永遠(yuǎn)無法離開時,返回 true绣硝。否則蜻势,返回 false。
提示
1 <= instructions.length <= 100
instructions[i] 在 {'G', 'L', 'R'} 中
示例
示例 1
輸入:"GGLLGG"
輸出:true
解釋:
機(jī)器人從 (0,0) 移動到 (0,2)鹉胖,轉(zhuǎn) 180 度握玛,然后回到 (0,0)。
重復(fù)這些指令次员,機(jī)器人將保持在以原點為中心败许,2 為半徑的環(huán)中進(jìn)行移動。
示例 2
輸入:"GG"
輸出:false
解釋:
機(jī)器人無限向北移動淑蔚。
示例 3
輸入:"GL"
輸出:true
解釋:
機(jī)器人按 (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... 進(jìn)行移動市殷。
解答
我們實例化一個機(jī)器人類,包含三個方法:向前走一步刹衫,左轉(zhuǎn)和右轉(zhuǎn)醋寝,包含若干屬性:當(dāng)前位置,當(dāng)前方向等带迟。根據(jù)指令調(diào)用即可音羞。
關(guān)于回到原點的問題,我們只需要將指令重復(fù)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]
如有疑問或建議搀继,歡迎評論區(qū)留言~