美文网首页
LeetCode:模拟行走机器人

LeetCode:模拟行走机器人

作者: alex很累 | 来源:发表于2022-10-09 22:21 被阅读0次

    874. 模拟行走机器人

    问题描述

    机器人在一个无限大小的 XY 网格平面上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令 commands
    -2 :向左转 90 度
    -1 :向右转 90 度
    1 <= x <= 9 :向前移动 x 个单位长度
    在网格上有一些格子被视为障碍物 obstacles 。第 i 个障碍物位于网格点 obstacles[i] = (xi, yi)
    机器人无法走到障碍物上,它将会停留在障碍物的前一个网格方块上,但仍然可以继续尝试进行该路线的其余部分。
    返回从原点到机器人所有经过的路径点(坐标为整数)的最大欧式距离的平方。(即,如果距离为 5 ,则返回 25 )

    注意:
    北表示 +Y 方向。
    东表示 +X 方向。
    南表示 -Y 方向。
    西表示 -X 方向。

    提示:
    1 <= commands.length <= 104
    commands[i] is one of the values in the list [-2,-1,1,2,3,4,5,6,7,8,9].
    0 <= obstacles.length <= 104
    -3 * 104 <= xi, yi <= 3 * 104

    示例

    输入:commands = [4,-1,3], obstacles = []
    输出:25
    解释:
    机器人开始位于 (0, 0):
    1. 向北移动 4 个单位,到达 (0, 4)
    2. 右转
    3. 向东移动 3 个单位,到达 (3, 4)
    距离原点最远的是 (3, 4) ,距离为 32 + 42 = 25
    
    输入:commands = [4,-1,4,-2,4], obstacles = [[2,4]]
    输出:65
    解释:机器人开始位于 (0, 0):
    1. 向北移动 4 个单位,到达 (0, 4)
    2. 右转
    3. 向东移动 1 个单位,然后被位于 (2, 4) 的障碍物阻挡,机器人停在 (1, 4)
    4. 左转
    5. 向北走 4 个单位,到达 (1, 8)
    距离原点最远的是 (1, 8) ,距离为 12 + 82 = 65
    

    解题思路

    模拟法+哈希
    模拟机器人行走即可,要注意的是利用哈希表快速查找障碍物:
    a. 可以将障碍物坐标组成组成“x,y”的字符串放入哈希表;
    b. 可以Long.valueOf(x + 30000) << 16) + y + 30000存成一个long,其中30000是为了负数转正数。

    代码示例(JAVA)

    class Solution {
        public int robotSim(int[] commands, int[][] obstacles) {
            int result = 0;
            int x = 0, y = 0;
            int index = 0;
            // 方向增量
            int[] arrX = {0, 1, 0, -1};
            int[] arrY = {1, 0, -1, 0};
            // 将障碍物坐标存入hash,加快查找效率
            Set<Long> set = new HashSet<>();
            for (int[] obstacle : obstacles) {
                set.add((Long.valueOf(obstacle[0] + 30000) << 16) + obstacle[1] + 30000);
            }
    
            for (int command : commands) {
                // 向右转
                if (command == -1) {
                    index = (index + 1) % 4;
                }else if (command == -2) {
                    // 向左转
                    index = (4 + index - 1) % 4;
                } else {
                    // 行走
                    for (int i = 0; i < command; i++) {
                        int newX = x + arrX[index];
                        int newY = y + arrY[index];
                        if (set.contains((Long.valueOf(newX + 30000) << 16) + newY + 30000)) {
                            break;
                        }
                        x = newX;
                        y = newY;
                        result = Math.max(result, Math.abs(x * x) + Math.abs(y * y));
                    }
                }
            }
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode:模拟行走机器人

          本文链接:https://www.haomeiwen.com/subject/qtynartx.html