Walking Robot Simulation

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 degrees
  • 1 <= x <= 9: move forward x 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

  

转载于:https://www.cnblogs.com/m2492565210/p/9448888.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值