• 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
    

      

  • 相关阅读:
    Eclipse中支持js提示
    数据库命名规则
    JavaWeb 命名规则
    Ajax&json
    js中,var 修饰变量名和不修饰的区别
    javaScript知识点
    Bootstrap 栅格系统
    文本框如果不输入任何内容提交过后是一个空字符串还是null
    根据汇总数量依次扣减的SQL新语法
    asp.net中使用forms验证
  • 原文地址:https://www.cnblogs.com/m2492565210/p/9448888.html
Copyright © 2020-2023  润新知