zoukankan      html  css  js  c++  java
  • 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
    

      

  • 相关阅读:
    pat1111-1120
    pat1101-1110
    pat1091-1100
    pat1081-1090
    pat1071-1080
    pat1061-1070
    2017华为软件精英挑战赛总结
    pat1051-1060
    【转】WPF中PasswordBox控件的Password属性的数据绑定
    Python学习-41.Python中的断言
  • 原文地址:https://www.cnblogs.com/m2492565210/p/9448888.html
Copyright © 2011-2022 走看看