A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands:
-2
: turn left 90 degrees-1
: turn right 90 degrees1 <= x <= 9
: move forwardx
units
Some of the grid squares are obstacles.
The i
-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])
If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.)
Return the square of the maximum Euclidean distance that the robot will be from the origin.
class Solution(object): def robotSim(self, commands, obstacles): """ :type commands: List[int] :type obstacles: List[List[int]] :rtype: int """ x = y = distance = direct = 0 //x,y对应于坐标轴上的位置,distance欧几里得平方距离,direct方向,取值0、1、2、3,与step步长对应,代表了坐标轴的上、左、下、右四个方向 step = [(0,1), (-1,0), (0,-1), (1,0)] obstacles = set(map(tuple, obstacles)) for command in commands: if command == -2: direct = (direct + 1) % 4 //沿坐标轴左旋转 elif command == -1: direct = (direct - 1) % 4 //沿坐标轴右旋转 else: delx, dely = step[direct] //当前方向步长 while command and (x + delx, y + dely) not in obstacles: x += delx y += dely command -= 1 //每次走一小步,并作检测 distance = max(distance, x**2 + y**2) return distance