问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4038 访问。

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

-2:向左转 90 度

-1:向右转 90 度

1 <= x <= 9:向前移动 x 个单位长度

在网格上有一些格子被视为障碍物。

第 i 个障碍物位于网格点  (obstacles[i][0], obstacles[i][1])

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

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

输入: commands = [4,-1,3], obstacles = []

输出: 25

解释: 机器人将会到达 (3, 4)

输入: commands = [4,-1,4,-2,4], obstacles = [[2,4]]

输出: 65

解释: 机器人在左转走到 (1, 8) 之前将被困在 (1, 4) 处

提示:

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

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.

Input: commands = [4,-1,3], obstacles = []

Output: 25

Explanation: robot will go to (3, 4)

Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]

Output: 65

Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)

Note:

  • 0 <= commands.length <= 10000
  • 0 <= obstacles.length <= 10000
  • -30000 <= obstacle[i][0] <= 30000
  • -30000 <= obstacle[i][1] <= 30000
  • The answer is guaranteed to be less than 2 ^ 31.

示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4038 访问。

public class Program {

    public static void Main(string[] args) {
var commands = new int[] { 4, -1, 3 };
var obstacles = new int[][] { }; var res = RobotSim(commands, obstacles);
Console.WriteLine(res); commands = new int[] { 4, -1, 4, -2, 4 };
obstacles = new int[][] { new int[] { 2, 4 } }; res = RobotSim2(commands, obstacles);
Console.WriteLine(res); commands = new int[] { 1, -1, 5, -2, 9 };
obstacles = new int[][] { new int[] { 1, 2 } }; res = RobotSim3(commands, obstacles);
Console.WriteLine(res); Console.ReadKey();
} public enum Direction {
Up = 0,
Left = 1,
Down = 2,
Right = 3
} private static void ComputerDirection(ref Direction direction, int cmd) {
if(cmd == -2) {
//向左转 90 度
if(direction == Direction.Right) {
direction = Direction.Up;
} else direction++;
} else if(cmd == -1) {
//向右转 90 度
if(direction == Direction.Up) {
direction = Direction.Right;
} else direction--;
}
} public static int RobotSim(int[] commands, int[][] obstacles) {
//传统解法
var x = 0;
var y = 0;
var move = 0;
var curDirection = Direction.Up;
var distance = 0;
var obset = new HashSet<KeyValuePair<int, int>>();
foreach(var obs in obstacles) {
obset.Add(new KeyValuePair<int, int>(obs[0], obs[1]));
}
foreach(var cmd in commands) {
if(cmd == -1 || cmd == -2) ComputerDirection(ref curDirection, cmd);
else {
move = 0;
switch(curDirection) {
case Direction.Up:
while(++move <= cmd) {
if(obset.Contains(new KeyValuePair<int, int>(x, y + move))) break;
}
y += --move;
break;
case Direction.Left:
while(++move <= cmd) {
if(obset.Contains(new KeyValuePair<int, int>(x - move, y))) break;
}
x -= --move;
break;
case Direction.Down:
while(++move <= cmd) {
if(obset.Contains(new KeyValuePair<int, int>(x, y - move))) break;
}
y -= --move;
break;
case Direction.Right:
while(++move <= cmd) {
if(obset.Contains(new KeyValuePair<int, int>(x + move, y))) break;
}
x += --move;
break;
default:
break;
}
distance = Math.Max(distance, x * x + y * y);
}
}
return distance;
} public static int RobotSim2(int[] commands, int[][] obstacles) {
//优化方向的解析
//可以理解为方向向量
var direc = new List<KeyValuePair<int, int>>
{
{ new KeyValuePair<int, int>(0, 1) }, //上
{ new KeyValuePair<int, int>(1, 0) }, //右
{ new KeyValuePair<int, int>(0, -1) }, //下
{ new KeyValuePair<int, int>(-1, 0) } //左
};
//障碍物哈希表,加速障碍物的判定
var obset = new HashSet<KeyValuePair<int, int>>();
//x 值和 y 值计数
var x = 0;
var y = 0;
//最大距离
var distance = 0;
//方向值
var direction = 0;
//初始化障碍物
foreach(var obs in obstacles) {
obset.Add(new KeyValuePair<int, int>(obs[0], obs[1]));
}
//解析每个命令
foreach(var cmd in commands) {
//0,1,2,3代表 4个方向,请自行分析
if(cmd == -2) {
//向左转 90 度
direction = (direction + 3) % 4;
} else if(cmd == -1) {
//向右转 90 度
direction = (direction + 1) % 4;
} else {
//先记录命令的值,因为 cmd 为迭代变量,C#语法规定不允许变更
var count = cmd;
//在水平方向或垂直方向上分析障碍物
//记数每次 -1,直接 0 时为止
//count-- 不能写成 --count,请自行分析
while(count-- > 0) {
//记录移动到的位置
var dx = x + direc[direction].Key;
var dy = y + direc[direction].Value;
//障碍物判定,使用哈希加速查找
//因为哈希查找为 O(1) 时间复杂度,即为常量时间复杂度
if(obset.Contains(new KeyValuePair<int, int>(dx, dy))) {
//若包含说明有障碍物,直接退出循环
break;
}
//若不包含说明没有障碍物
//更新 x 和 y 的值
x = dx;
y = dy;
//每次计算距离
distance = Math.Max(distance, x * x + y * y);
}
}
}
//返回最大距离
return distance;
} public static int RobotSim3(int[] commands, int[][] obstacles) {
//基本思路同 RobotSim2
//此解法参考 LeetCode 官方【阅读】模块
//实测效率略快于 RobotSim2 的解法
var direc = new List<KeyValuePair<int, int>>
{
{ new KeyValuePair<int, int>(0, 1) },
{ new KeyValuePair<int, int>(1, 0) },
{ new KeyValuePair<int, int>(0, -1) },
{ new KeyValuePair<int, int>(-1, 0) }
};
var obset = new HashSet<long>();
var x = 0;
var y = 0;
var distance = 0;
var direction = 0;
//优化编码
foreach(var obs in obstacles) {
long ox = (long)obs[0] + 30000;
long oy = (long)obs[1] + 30000;
obset.Add((ox << 16) + oy);
}
foreach(var cmd in commands) {
if(cmd == -2) {
direction = (direction + 3) % 4;
} else if(cmd == -1) {
direction = (direction + 1) % 4;
} else {
var count = cmd;
while(count-- > 0) {
var dx = x + direc[direction].Key;
var dy = y + direc[direction].Value;
long code = (((long)dx + 30000) << 16) + ((long)dy + 30000);
//优化障碍物判定
if(obset.Contains(code)) {
break;
}
x = dx;
y = dy;
distance = Math.Max(distance, x * x + y * y);
}
}
}
return distance;
} }

以上给出3种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4038 访问。

25
65
125

分析:

设命令和障碍物的数量分别为 m 和 n,那么以上3种算法的时间复杂度应当均为   。

C#LeetCode刷题之#874-模拟行走机器人​​​​​​​(Walking Robot Simulation)的更多相关文章

  1. [Swift]LeetCode874. 模拟行走机器人 | Walking Robot Simulation

    A robot on an infinite grid starts at point (0, 0) and faces north.  The robot can receive one of th ...

  2. C#LeetCode刷题-贪心算法

    贪心算法篇 # 题名 刷题 通过率 难度 44 通配符匹配   17.8% 困难 45 跳跃游戏 II   25.5% 困难 55 跳跃游戏   30.6% 中等 122 买卖股票的最佳时机 II C ...

  3. LeetCode刷题总结-数组篇(中)

    本文接着上一篇文章<LeetCode刷题总结-数组篇(上)>,继续讲第二个常考问题:矩阵问题. 矩阵也可以称为二维数组.在LeetCode相关习题中,作者总结发现主要考点有:矩阵元素的遍历 ...

  4. LeetCode刷题专栏第一篇--思维导图&时间安排

    昨天是元宵节,过完元宵节相当于这个年正式过完了.不知道大家有没有投入继续投入紧张的学习工作中.年前我想开一个Leetcode刷题专栏,于是发了一个投票想了解大家的需求征集意见.投票于2019年2月1日 ...

  5. leetcode 刷题进展

    最近没发什么博客了 凑个数 我的leetcode刷题进展 https://gitee.com/def/leetcode_practice 个人以为 刷题在透不在多  前200的吃透了 足以应付非算法岗 ...

  6. LeetCode刷题指南(字符串)

    作者:CYC2018 文章链接:https://github.com/CyC2018/CS-Notes/blob/master/docs/notes/Leetcode+%E9%A2%98%E8%A7% ...

  7. leetcode刷题记录--js

    leetcode刷题记录 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但 ...

  8. LeetCode刷题总结之双指针法

    Leetcode刷题总结 目前已经刷了50道题,从零开始刷题学到了很多精妙的解法和深刻的思想,因此想按方法对写过的题做一个总结 双指针法 双指针法有时也叫快慢指针,在数组里是用两个整型值代表下标,在链 ...

  9. Leetcode刷题记录(python3)

    Leetcode刷题记录(python3) 顺序刷题 1~5 ---1.两数之和 ---2.两数相加 ---3. 无重复字符的最长子串 ---4.寻找两个有序数组的中位数 ---5.最长回文子串 6- ...

随机推荐

  1. 循序渐进VUE+Element 前端应用开发(17)--- 菜单资源管理

    在权限管理系统中,菜单也属于权限控制的一个资源,应该直接应用于角色,和权限功能点一样,属于角色控制的一环.不同角色用户,登录系统后,出现的系统菜单是不同的.在VUE+Element 前端中,我们菜单结 ...

  2. Burp Suite Decoder Module - 解码模块

    官方参考链接:https://portswigger.net/burp/documentation/desktop/tools/decoder 该模块主要进行编码和解码,支持编码方式有:Plain,U ...

  3. R星游戏如何绑定二次验证码_虚拟MFA_两步验证_谷歌身份验证器?

    一般点账户名——设置——安全设置中开通虚拟MFA两步验证 具体步骤见链接 R星游戏如何绑定二次验证码_虚拟MFA_两步验证_谷歌身份验证器? 二次验证码小程序于谷歌身份验证器APP的优势 1.无需下载 ...

  4. python爬虫入门(5)----- 阿里巴巴供应商爬虫

    阿里巴巴供应商爬虫# 起因## 学了爬虫入门之后,打算找一个有难度的网站来实践,一开始打算找淘宝或者天猫(业界老大)来实践,但后续发现网上已经有很多这方面的项目,于是瞄上了阿里的国际网站阿里巴巴.开始 ...

  5. oracle SCN推进恢复数据库 简单记录

    由于是在内网专用机器上操作,没有日志记录,下面做个简单记录:   前几天某供电局的的一个老数据库存储挂了,数据全部丢失,该库没有开归档,没接备份,怎么恢复? 由于存储损坏严重,从存储恢复不好搞. 好在 ...

  6. Vue中数组元素被替换,页面没有动态展示

    原始代码 页面没有相应goodsList替换,打印goodsList数据已经被替换: (借用https://www.cnblogs.com/belongs-to-qinghua/p/11112613. ...

  7. PHP preg_replace_callback_array() 函数

    preg_replace_callback_array 函数执行一个正则表达式搜索并且使用一个回调进行替换.高佣联盟 www.cgewang.com 该函数在 PHP7+ 版本支持. 语法 mixed ...

  8. Blob分析之bottle.hdev

    * 分割读取啤酒瓶子上的数字* bottle.hdev: Segment and read numbers on a beer bottle* 第0步* Step 0: Preparations*定义 ...

  9. 5.29 省选模拟赛 树的染色 dp 最优性优化

    LINK:树的染色 考场上以为这道题要爆蛋了 没想到 推出正解来了. 反正是先写了爆搜的 爆搜最近越写越熟练了 容易想到dp 容易设出状态 f[i][j]表示以i为根的子树内白色的值为j此时黑色的值怎 ...

  10. 题解 [SHOI2002]滑雪

    记忆化搜索$||dp||$剪枝 先讲方法,代码待会上 方法一:记忆化搜索 这个方法不怎么解释,就是每搜索完一个高度的最长路径记录一下,以后搜索其他的点时如果走到了这条路就直接用记录的值计算就是了 方法 ...