领扣LintCode算法问题答案-1493. 模拟行走机器人

    科技2022-07-13  129

    领扣LintCode算法问题答案-1493. 模拟行走机器人

    目录

    1493. 模拟行走机器人描述样例 1:样例 2: 题解鸣谢

    1493. 模拟行走机器人

    描述

    机器人在一个无限大小的网格上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令:

    -2:向左转 90 度-1:向右转 90 度1 <= x <= 9:向前移动 x 个单位长度

    在网格上有一些格子被视为障碍物。 第 i 个障碍物位于网格点 (obstacles[i][0], obstacles[i][1])

    如果机器人试图走到障碍物上方,那么它将停留在障碍物的前一个网格方块上,但仍然可以继续该路线的其余部分。

    返回从原点到机器人的最大欧式距离的平方。

    0 <= commands.length <= 100000 <= obstacles.length <= 10000-30000 <= obstacle[i][0] <= 30000-30000 <= obstacle[i][1] <= 30000答案保证小于 2 ^ 31

    样例 1:

    输入: commands = [4,-1,3], obstacles = [] 输出: 25 解释: 机器人将会到达 (3, 4)

    样例 2:

    输入: commands = [4,-1,4,-2,4], obstacles = [[2,4]] 输出: 65 解释: 机器人在左转走到 (1, 8) 之前将被困在 (1, 4) 处

    题解

    public class Solution { /** * @param commands: type: List[int] * @param obstacles: type: List[List[int]] * @return: Return the square of the maximum Euclidean distance */ public int robotSim(int[] commands, int[][] obstacles) { // write your code here Map<Integer, Set<Integer>> obstaclesMap = new HashMap<>(); for (int[] p : obstacles) { Set<Integer> l = obstaclesMap.get(p[0]); if (l == null) { l = new HashSet<>(); obstaclesMap.put(p[0], l); } l.add(p[1]); } int[] location = new int[]{0, 0}; Direction d = Direction.N; for (int c : commands) { switch (c) { case -2: d = d.toLeft(); break; case -1: d = d.toRight(); break; default: int[] nl = new int[2]; nl[0] = location[0]; nl[1] = location[1]; for (int i = 0; i < c; i++) { Set<Integer> ys = obstaclesMap.get(nl[0] + d.getX()); if (ys != null && ys.contains(nl[1] + d.getY())) { break; } nl[0] += d.getX(); nl[1] += d.getY(); } location[0] = nl[0]; location[1] = nl[1]; System.out.println("l:"+location[0] + "," + location[1]); break; } } return location[0] * location[0] + location[1] * location[1]; } enum Direction { E(1, 0) { @Override public Direction toLeft() { return N; } @Override public Direction toRight() { return S; } }, S(0, -1) { @Override public Direction toLeft() { return E; } @Override public Direction toRight() { return W; } }, W(-1, 0) { @Override public Direction toLeft() { return S; } @Override public Direction toRight() { return N; } }, N(0, 1) { @Override public Direction toLeft() { return W; } @Override public Direction toRight() { return E; } }, ; private final int x; private final int y; Direction(int x, int y) { this.x = x; this.y = y; } public abstract Direction toLeft(); public abstract Direction toRight(); public int getX() { return x; } public int getY() { return y; } } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.010, SQL: 8