zoukankan      html  css  js  c++  java
  • 【leetcode】LCP 3. Programmable Robot

    题目如下:

    力扣团队买了一个可编程机器人,机器人初始位置在原点(0, 0)。小伙伴事先给机器人输入一串指令command,机器人就会无限循环这条指令的步骤进行移动。指令有两种:

    U: 向y轴正方向移动一格
    R: 向x轴正方向移动一格。
    不幸的是,在 xy 平面上还有一些障碍物,他们的坐标用obstacles表示。机器人一旦碰到障碍物就会被损毁。

    给定终点坐标(x, y),返回机器人能否完好地到达终点。如果能,返回true;否则返回false。

    示例 1:

    输入:command = "URR", obstacles = [], x = 3, y = 2
    输出:true
    解释:U(0, 1) -> R(1, 1) -> R(2, 1) -> U(2, 2) -> R(3, 2)。
    示例 2:

    输入:command = "URR", obstacles = [[2, 2]], x = 3, y = 2
    输出:false
    解释:机器人在到达终点前会碰到(2, 2)的障碍物。
    示例 3:

    输入:command = "URR", obstacles = [[4, 2]], x = 3, y = 2
    输出:true
    解释:到达终点后,再碰到障碍物也不影响返回结果。
     

    限制:

    2 <= command的长度 <= 1000
    command由U,R构成,且至少有一个U,至少有一个R
    0 <= x <= 1e9, 0 <= y <= 1e9
    0 <= obstacles的长度 <= 1000
    obstacles[i]不为原点或者终点

    解题思路:机器人的轨迹是有规律的。首先可以分别求出command中U和R的数量,然后遍历一次command,记录机器人运行时候经过的坐标。假如其中有一个坐标为(x1,y1),那么这个点接下来的轨迹满足 x1 = x1*r_count*n, y 1 = y1*u_count*n,n为正整数。所以只需要判断obstacles是否满足上面的方程即可。最后要注意的一点是也要判断终点是否满足这个方程,如果不满足说明从起点开始,即使没遇到任何障碍也无法到达终点。

    代码如下:

    class Solution(object):
        def robot(self, command, obstacles, x, y):
            """
            :type command: str
            :type obstacles: List[List[int]]
            :type x: int
            :type y: int
            :rtype: bool
            """
            u_count = command.count('U')
            r_count = command.count('R')
            path = [[0,0]]
            cx,cy = 0,0
            for c in command:
                if c == 'U':cy += 1
                else: cx += 1
                path.append([cx,cy])
            for (ox,oy) in obstacles:
                if ox > x or oy > y:continue
                for (px,py) in path:
                    if (ox - px) % r_count == 0 and (oy - py) % u_count == 0 and (ox - px) / r_count  == (oy - py) / u_count :
                        return False
    
            #check can reach exit
            for (px, py) in path:
                if (x - px) % r_count == 0 and (y - py) % u_count == 0 and (x - px) / r_count == (y - py) / u_count:
                    return True
    
            return False
  • 相关阅读:
    e621. Activating a Keystroke When Any Child Component Has Focus
    e587. Filling Basic Shapes
    e591. Drawing Simple Text
    e595. Drawing an Image
    e586. Drawing Simple Shapes
    e636. Listening to All Key Events Before Delivery to Focused Component
    在 PL/SQL 块的哪部分可以对初始变量赋予新值? (选择1项)
    Oracle数据库中,在SQL语句中连接字符串的方法是哪个?(选择1项)
    你判断下面语句,有什么作用?(单选)
    Oracle数据库表空间与数据文件的关系描述正确的是( )
  • 原文地址:https://www.cnblogs.com/seyjs/p/11605022.html
Copyright © 2011-2022 走看看