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
    

      

  • 相关阅读:
    计算机知识
    试题:论需求分析方法及应用
    试题:论信息系统开发方法及应用
    爬虫数据存储——安装docker和ElasticSearch(基于Centos7)
    go并发版爬虫
    go单任务版爬虫
    可变类型与不可变类型
    基本数据类型内置方法
    @submit.native.prevent作用
    获取当月第一天,今天的日期的方法
  • 原文地址:https://www.cnblogs.com/m2492565210/p/9448888.html
Copyright © 2011-2022 走看看