zoukankan      html  css  js  c++  java
  • leetcode LCP 3. 机器人大冒险 java

    题目:

    力扣团队买了一个可编程机器人,机器人初始位置在原点(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]不为原点或者终点

    解题:

    class Solution {
        //获取执行指令中UR的个数
        public int[] getDirectionCount(String command, int length) {
            int[] count = new int[]{0, 0};
            char[] charArr = command.toCharArray();
            for (int i = 0; i < length; i++) {
                if (charArr[i] == 'U') {
                    count[0]++;
                } else {
                    count[1]++;
                }
            }
            return count;
        }
    
        //方法如上,但是提交后,会涉及到内存溢出,原因是有的x+y非常大,导致command拼接的次数相当巨大,所以优化也在command拼接那里优化
        //优化后通过command的长度来获取移动指令中UR的次数
        //判断能够从起点(0,0)通过command命令到达(x,y)点
        public boolean getCount(int x, int y, String command) {
            int times = (x + y) / command.length();
            int extra = (x + y) % command.length();
            int[] yxStep = getDirectionCount(command, command.length());
            int[] yxStepEx = getDirectionCount(command, extra);
            yxStep[0] = yxStep[0] * times + yxStepEx[0];
            yxStep[1] = yxStep[1] * times + yxStepEx[1];
            return y == yxStep[0] && x == yxStep[1];
        }
    
        //补全:开始方法
        public boolean robot(String command, int[][] obstacles, int x, int y) {
            for (int[] point : obstacles) {
                int pX = point[0];
                int pY = point[1];
                if (pX + pY > x + y) { //障碍点不在起终点的范围内
                    continue;
                }
                if (getCount(pX, pY, command)) { //是否经过障碍点
                    return false;
                }
            }
            return getCount(x, y, command);//是否经过终点
    
        }
    }
  • 相关阅读:
    「网易官方」极客战记(codecombat)攻略-沙漠-拦截-interception
    「网易官方」极客战记(codecombat)攻略-沙漠-十字路口-crossroads
    「网易官方」极客战记(codecombat)攻略-沙漠-Sarven 的距离-sarven-gaps
    jenkins添加节点
    jenkins document
    docker ssh连接登录
    docker 切换工作目录和用户
    普通用户su到root免密码
    设置linux服务或脚本开机启动
    python class 私有变量
  • 原文地址:https://www.cnblogs.com/yanhowever/p/11980271.html
Copyright © 2011-2022 走看看