1. 題目
機器人在一個無限大小的網格上行走,從點 (0, 0) 處開始出發,面向北方。該機器人可以接收以下三種類型的命令:
-2:向左轉 90 度
-1:向右轉 90 度
1 <= x <= 9:向前移動 x 個單位長度
在網格上有一些格子被視爲障礙物。
第 i 個障礙物位於網格點 (obstacles[i][0], obstacles[i][1])
機器人無法走到障礙物上,它將會停留在障礙物的前一個網格方塊上,但仍然可以繼續該路線的其餘部分。
返回從原點到機器人的最大歐式距離的平方。
示例 2:
輸入: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
輸出: 65
解釋: 機器人在左轉走到 (1, 8) 之前將被困在 (1, 4) 處
提示:
0 <= commands.length <= 10000
0 <= obstacles.length <= 10000
-30000 <= obstacle[i][0] <= 30000
-30000 <= obstacle[i][1] <= 30000
答案保證小於 2 ^ 31
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/walking-robot-simulation
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2. 代碼
真是模擬場景題,技巧是使用集合記錄障礙。
class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
x = 0
y = 0
#directions = ['n','e','s','w']
dx = [0,1,0,-1]
dy = [1,0,-1,0]
d_inx = 0
ob_set = set()
for ob in obstacles:
ob_set.add((ob[0],ob[1]))
def move(x,y,k, d_inx):
for i in range(1,k+1):
if (x+dx[d_inx],y+dy[d_inx]) in ob_set:
return x,y
x = x+dx[d_inx]
y = y+dy[d_inx]
return x,y
res = 0
for c in commands:
if c>0:
x,y = move(x,y,c,d_inx)
elif c == -1:
d_inx = (d_inx+1)%4
elif c == -2:
d_inx = (d_inx+3)%4
res = max(res,x**2+y**2)
return res