题目地址:https://leetcode-cn.com/problems/the-maze-ii/

题目描述

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, find the shortest distance for the ball to stop at the destination. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1.

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: 12 Explanation: One shortest way is : left -> down -> left -> down -> right -> down -> right.
The total distance is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.

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: -1 Explanation: There is no way for the ball to stop at the destination.

Note:

  1. There is only one ball and one destination in the maze.
  2. Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
  3. 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.
  4. The maze contains at least 2 empty spaces, and both the width and height of the maze won’t exceed 100.

题目大意

小球可以向某个方向一直滚动,当撞到边缘或者墙壁时才停止,每次停止时才可以选择下个移动的方向。问小球是否能从起点出发恰好停在目的地,并返回小球滚动到目的地需要的最少步数。

解题方法

BFS

题目要我们求最少的移动步数,很显然我们使用BFS解决。一般的迷宫问题只会移动一个格子,但是这个题目要求我们撞到墙壁才停止,所以我们需要遍历四个方向,判断四个方向分别撞到墙壁时移动的步数和结束位置。当小球移动到该结束位置总的步数比历史上所有的位置都小,该结束位置放入队列中。

一般BFS需要有个visited数组,用来判断每个位置是否访问过,从而判断新位置是否加入队列中。但是这个题目不需要,因为只有当到达一个结置位置总的步数比以前到达这个位置的步数小的时候,才会加入队列,所以是有限制条件的,结果会是有限的,不会无限循环下去。

代码里使用了dp作为访问每个位置的最小步数,默认是INT_MAX。从起点开始,计算出小球能访问到的所有位置,直至再运动已经不能让所有可以停止的点的访问步数缩小时停止。最后返回结束位置的步数。

C++代码如下:

class Solution {
public:
int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
const int M = maze.size();
const int N = maze[0].size();
vector<vector<int>> dp(M, vector<int>(N, INT_MAX));
queue<vector<int>> que;
que.push(start);
dp[start[0]][start[1]] = 0;
int count = 0;
while (!que.empty()) {
int size = que.size();
vector<int> start = que.front(); que.pop();
for (auto dir : dirs) {
vector<int> end(2, 0);
int step = rolling(maze, dir, start, end);
if (dp[end[0]][end[1]] > dp[start[0]][start[1]] + step) {
dp[end[0]][end[1]] = dp[start[0]][start[1]] + step;
que.push(end);
}
}
}
return dp[destination[0]][destination[1]] == INT_MAX ? -1 : dp[destination[0]][destination[1]];
}
private:
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int rolling(vector<vector<int>>& maze, vector<int>& curdir, vector<int>& start, vector<int>& end) {
end = start;
int step = 0;
while (true) {
int nxt_x = end[0] + curdir[0];
int nxt_y = end[1] + curdir[1];
if (nxt_x < 0 || nxt_x >= maze.size() || nxt_y < 0 || nxt_y >= maze[0].size()
|| maze[nxt_x][nxt_y] == 1) {
break;
}
end[0] = nxt_x;
end[1] = nxt_y;
step ++;
}
return step;
}
};

参考资料:https://leetcode-cn.com/problems/the-maze-ii/solution/c-bfs-by-sheng-ben-xin/

日期

2019 年 9 月 20 日 —— 是选择中国互联网式加班?还是外企式养生?

【LeetCode】505. The Maze II 解题报告(C++)的更多相关文章

  1. 【LeetCode】47. Permutations II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:递归 方法二:回溯法 日期 题目地址:htt ...

  2. 【LeetCode】90. Subsets II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 回溯法 日期 题目地址:https://leet ...

  3. [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 ...

  4. [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 ...

  5. LeetCode 505. The Maze II

    原题链接在这里:https://leetcode.com/problems/the-maze-ii/ 题目: There is a ball in a maze with empty spaces a ...

  6. 【LeetCode】275. H-Index II 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/h-index- ...

  7. 【LeetCode】52. N-Queens II 解题报告(Python & C+)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 全排列函数 回溯法 日期 题目地址:https:// ...

  8. 【LeetCode】454. 4Sum II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcod ...

  9. LeetCode: Pascal's Triangle II 解题报告

    Pascal's Triangle II Total Accepted: 19384 Total Submissions: 63446 My Submissions Question Solution ...

随机推荐

  1. W10: Warning: Changing a readonly file使用vi/vim报错问题解决

    使用vi/vim编辑文件的时候出现W10: Warning: Changing a readonly file报错 解决方法: 一.强制保存退出 :wq! 二.ll 查询文件属主,使用属主赋予权限 c ...

  2. DNS域名解析全过程

    一张图看懂DNS域名解析全过程   DNS域名解析是互联网上非常重要的一项服务,上网冲浪(还有人在用这个词吗?)伴随着大量DNS服务来支撑,而对于网站运营来说,DNS域名解析的稳定可靠,意味着更多用户 ...

  3. EXCEL-排名前三名显示小红旗,后三名显示小黑旗

    总结(用的WPS):第一步:用=IF(RANK(数值,引用范围) <=3,"小红旗",IF(RANK(数值,引用,1) <=3,"小黑旗",&quo ...

  4. .net与java建立WebService再互相调用

    A: .net建立WebService,在java中调用. 1.在vs中新建web 简单修改一下Service.cs的[WebMethod]代码: using System; using System ...

  5. Yarn 公平调度器案例

    目录 公平调度器案例 需求 配置多队列的公平调度器 1 修改yarn-site.xml文件,加入以下从参数 2 配置fair-scheduler.xml 3 分发配置文件重启yarn 4 测试提交任务 ...

  6. A Child's History of England.9

    But, first, as it was important to know how numerous those pestilent Danes were, and how they were f ...

  7. Spark检查点机制

    Spark中对于数据的保存除了持久化操作之外,还提供了一种检查点的机制,检查点(本质是通过将RDD写入Disk做检查点)是为了通过lineage(血统)做容错的辅助,lineage过长会造成容错成本过 ...

  8. java多线程 并发编程

    一.多线程 1.操作系统有两个容易混淆的概念,进程和线程. 进程:一个计算机程序的运行实例,包含了需要执行的指令:有自己的独立地址空间,包含程序内容和数据:不同进程的地址空间是互相隔离的:进程拥有各种 ...

  9. vue2 中的 export import

    vue中组件的引用嵌套通过export import语法链接 Nodejs中的 export import P1.js export default { name: 'P1' } index.js i ...

  10. EM配置问题

    配置EM,首先要保证dbconsole在运行. C:\Users\dingqi>emctl start dbconsoleEnvironment variable ORACLE_UNQNAME ...