"""
2023.04.11| 1041. 困於環中的機器人
https://leetcode.cn/problems/robot-bounded-in-circle/
題目分析:
這題難度是中等,實際上比較簡單;
G=向前;L=左轉90度;R=右轉90度
理論:模擬
用座標軸來進行機器人的行走模擬,關鍵是用一組數據進行方向計算
1.定義轉向值列表direction,分別表示北東南西;direct表示當前方向
2.遍歷instructions中字符=ch
3.判斷ch
3.1 如果=G,根據direction行走
3.2 如果=L,更新方向
3.3 如果=R,更新方向
4.判斷x,y是否是原點;direct是否正確
注意/難點:
方向判斷需要%,不然direct會越界溢出
"""
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
"""初始化direction,和direct表示移東方向和當前方向
北/上 東/右 南/下 西/左
direct 0 1 2 3
x 0 +1 0 -1
y +1 0 -1 0
"""
direction=[[0,1],[1,0],[0,-1],[-1,0]] #x,y的移動步數
direct=0 #初始化變量
x,y=0,0 #x,y座標軸位置
for ch in instructions: #遍歷字符
if ch=="G": #向前
x+=direction[direct][0] #x軸方向前進步數
y+=direction[direct][1] #y軸方向前進步數
elif ch=="L": #左轉90度
direct=(direct+3)%4 #重新計算方向
elif ch=="R": #右轉90度
direct=(direct+1)%4 #重新計算方向
print(f'x={x}; y={y}')
#如果回到原點或者方向不朝北,必走不出平面
if x==0 and y==0 or direct!=0:
return True
return False #不滿足條件返回
instructions = "GGLLGG"
ans=Solution().isRobotBounded(instructions)
print(ans)
模擬過程如下: