[LeetCode] 490. The Maze 迷宫
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.
Example 1
Input 1: a maze represented by a 2D array 0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0 Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4) Output: true
Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.
Example 2
Input 1: a maze represented by a 2D array 0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0 Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (3, 2) Output: false
Explanation: There is no way for the ball to stop at the destination.
Note:
- There is only one ball and one destination in the maze.
- Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
- The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
- The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.
这道题让我们遍历迷宫,但是与以往不同的是,这次迷宫是有一个滚动的小球,这样就不是每次只走一步了,而是朝某一个方向一直滚,直到遇到墙或者边缘才停下来,博主记得貌似之前在手机上玩过类似的游戏。那么其实还是要用 DFS 或者 BFS 来解,只不过需要做一些修改。先来看 DFS 的解法,用 DFS 的同时最好能用上优化,即记录中间的结果,这样可以避免重复运算,提高效率。这里用二维记忆数组 memo 来保存中间结果,然后用 maze 数组本身通过将0改为 -1 来记录某个点是否被访问过,这道题的难点是在于处理一直滚的情况,其实也不难,有了方向,只要一直在那个方向上往前走,每次判读是否越界了或者是否遇到墙了即可,然后对于新位置继续调用递归函数,参见代码如下:
解法一:
class Solution {
public:
vector<vector<int>> dirs{{,-},{-,},{,},{,}};
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {int m = maze.size(), n = maze[].size();
return helper(maze, start[], start[], destination[], destination[]);
}
bool helper(vector<vector<int>>& maze, int i, int j, int di, int dj) {
if (i == di && j == dj) return true;
bool res = false;
int m = maze.size(), n = maze[].size();
maze[i][j] = -;
for (auto dir : dirs) {
int x = i, y = j;
while (x >= && x < m && y >= && y < n && maze[x][y] != ) {
x += dir[]; y += dir[];
}
x -= dir[]; y -= dir[];
if (maze[x][y] != -) {
res |= helper(maze, x, y, di, dj);
}
}
return res;
}
};
同样的道理,对于 BFS 的实现需要用到队列 queue,在对于一直滚的处理跟上面相同,参见代码如下:
解法二:
class Solution {
public:
bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
if (maze.empty() || maze[].empty()) return true;
int m = maze.size(), n = maze[].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
vector<vector<int>> dirs{{,-},{-,},{,},{,}};
queue<pair<int, int>> q;
q.push({start[], start[]});
visited[start[]][start[]] = true;
while (!q.empty()) {
auto t = q.front(); q.pop();
if (t.first == destination[] && t.second == destination[]) return true;
for (auto dir : dirs) {
int x = t.first, y = t.second;
while (x >= && x < m && y >= && y < n && maze[x][y] == ) {
x += dir[]; y += dir[];
}
x -= dir[]; y -= dir[];
if (!visited[x][y]) {
visited[x][y] = true;
q.push({x, y});
}
}
}
return false;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/490
类似题目:
参考资料:
https://leetcode.com/problems/the-maze/
https://leetcode.com/problems/the-maze/discuss/97081/java-bfs-solution
https://leetcode.com/problems/the-maze/discuss/97112/Short-Java-DFS-13ms-Solution
[LeetCode] 490. The Maze 迷宫的更多相关文章
- LeetCode 490. The Maze
原题链接在这里:https://leetcode.com/problems/the-maze/ 题目: There is a ball in a maze with empty spaces and ...
- [LeetCode] 499. The Maze III 迷宫 III
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] 505. The Maze II 迷宫 II
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- 【南京邮电】maze 迷宫解法
[南京邮电]maze 迷宫解法 题目来源:南京邮电大学网络攻防训练平台. 题目下载地址:https://pan.baidu.com/s/1i5gLzIt (密码rijss) 0x0 初步分析 题目中给 ...
- [LeetCode] The Maze 迷宫
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] 505. The Maze II 迷宫之二
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- 【LeetCode】490. The Maze 解题报告 (C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS 日期 题目地址:https://leetcod ...
- 490. The Maze
原题链接:https://leetcode.com/articles/the-maze/ 这道题目是需要冲会员才能使用的,然而我个穷逼现在还是失业状态根本冲不起...以后如果把免费题目都刷完了的话,再 ...
- Maze迷宫问题(求最优解)
迷宫地形我们可以通过读文件的形式,通过已知入口逐个遍历坐标寻找通路. 文件如图: 每个坐标的位置用结构体来记录: struct Pos //位置坐标 { int _row; int _col; }; ...
随机推荐
- python随机选取目录下的若干个文件
个人记录用. python模块random argparse shutil import argparse parser = argparse.ArgumentParser() parser.add_ ...
- .NET Core on K8S快速入门课程--学习笔记
课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 目录 01-介绍K8s是什么 02-为什么要学习k8s 03-如何学习k8s ...
- Windows cmd 和 PowerShell 中文乱码问题解决
临时方案: 在命令行下输入:chcp 65001 长期方案: 要修改注册表,自己网上搜吧
- MySQL问题记录——定义timestamp类型的数据
MySQL问题记录——定义timestamp类型的数据 摘要:本文主要记录了在使用MySQL的过程中定义timestamp类型数据时遇到的问题以及解决方案. 问题重现 在Windows环境下安装MyS ...
- Winform中使用FastReport的PictureObject时通过代码设置图片源并使Image图片旋转90度
场景 FastReport安装包下载.安装.去除使用限制以及工具箱中添加控件: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10 ...
- ubuntu玩坏之后
昨天,安装openssh-server的时候,与openssh-client冲突,故卸载openssh-client然后重装openssh-server解决问题. 今天,想装emacs,发现跟perl ...
- weblogic删除域
彻底删除weblogic域的方法: 例如:删除域名为:fm_ump的域 第一步,删除域注册记录: [bofm@UAT02-BIZ-ZJCG-AP-008 Middleware]$ cd /home/s ...
- SQL注入:Cookie注入
什么是Cookie Cookie就是代表你身份的一串字符串,网站根据Cookie来识别你是谁,如果你获取了管理员的Cookie,就表示你可以无需密码直接登陆管理员账号. Cookie注入的原理 在动态 ...
- Tests in error:BlogApplicationTests.initializationError » IllegalState Unable to find a @Spri...【解决】
刚刚写完一个项目,准备打包,却发现无法打包. 然后认真排查了一下问题.发现少引入了一个插件. <plugin> <groupId>org.apache.maven.plugin ...
- pytest中怎么实现参数化?
我们在组自动化项目中,肯定会遇到需要数据驱动的地方,在unittest中我们直接采用ddt的方式,但是在pytest中我们不能用ddt来实现,所以我们采用了参数化的方式来实现 那么具体怎么完成这个参数 ...