|
| 1 | +# Time: O(n + k) |
| 2 | +# Space: O(k) |
| 3 | + |
| 4 | +# A robot on an infinite grid starts at point (0, 0) and faces north. |
| 5 | +# The robot can receive one of three possible types of commands: |
| 6 | +# - -2: turn left 90 degrees |
| 7 | +# - -1: turn right 90 degrees |
| 8 | +# - 1 <= x <= 9: move forward x units |
| 9 | +# |
| 10 | +# Some of the grid squares are obstacles. |
| 11 | +# |
| 12 | +# The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1]) |
| 13 | +# |
| 14 | +# If the robot would try to move onto them, |
| 15 | +# the robot stays on the previous grid square instead |
| 16 | +# (but still continues following the rest of the route.) |
| 17 | +# |
| 18 | +# Return the square of the maximum Euclidean distance that |
| 19 | +# the robot will be from the origin. |
| 20 | +# |
| 21 | +# Example 1: |
| 22 | +# |
| 23 | +# Input: commands = [4,-1,3], obstacles = [] |
| 24 | +# Output: 25 |
| 25 | +# Explanation: robot will go to (3, 4) |
| 26 | +# Example 2: |
| 27 | +# |
| 28 | +# Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]] |
| 29 | +# Output: 65 |
| 30 | +# Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8) |
| 31 | +# |
| 32 | +# Note: |
| 33 | +# - 0 <= commands.length <= 10000 |
| 34 | +# - 0 <= obstacles.length <= 10000 |
| 35 | +# - -30000 <= obstacle[i][0] <= 30000 |
| 36 | +# - -30000 <= obstacle[i][1] <= 30000 |
| 37 | +# - The answer is guaranteed to be less than 2 ^ 31. |
| 38 | + |
| 39 | +class Solution(object): |
| 40 | + def robotSim(self, commands, obstacles): |
| 41 | + """ |
| 42 | + :type commands: List[int] |
| 43 | + :type obstacles: List[List[int]] |
| 44 | + :rtype: int |
| 45 | + """ |
| 46 | + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] |
| 47 | + x, y, i = 0, 0, 0 |
| 48 | + lookup = set(map(tuple, obstacles)) |
| 49 | + result = 0 |
| 50 | + for cmd in commands: |
| 51 | + if cmd == -2: |
| 52 | + i = (i-1) % 4 |
| 53 | + elif cmd == -1: |
| 54 | + i = (i+1) % 4 |
| 55 | + else: |
| 56 | + for k in xrange(cmd): |
| 57 | + if (x+directions[i][0], y+directions[i][1]) not in lookup: |
| 58 | + x += directions[i][0] |
| 59 | + y += directions[i][1] |
| 60 | + result = max(result, x*x + y*y) |
| 61 | + return result |
0 commit comments