题目地址: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. R语言hist重叠图作法

    set.seed(1) h1<-hist(rnorm(1000,100,5)) h2<-hist(rnorm(1000,99,5)) plot(h2,col=rgb(255,0,0,50, ...

  2. DNS域名解析全过程

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

  3. Linux搭建rsync备份服务器备份

    环境: 1台rsync备份服务器,IP:10.0.0.188 1台rsync备份客户端,IP:10.0.0.51 备份数据需注意: 1. 在业务低谷时间进行备份 2. 进行备份限速 一.搭建rsync ...

  4. Oracle-left join两表关联只取B表匹配到的第一条记录【over partition by(分组后对组内数据排序)】

    背景:  A表.B表两表关联,关联出来的结果里B表有不止一条,需求是只要B表结果中的某一条(按某字段排序) 经过百度,发现 row_number() over(partition by a order ...

  5. 使用SpringBoot实现文件的上传

    使用SpringBoot实现文件的上传 springboot可以直接使用 org.springframework.web.multipart.MultipartFile 所以非常容易实现 一.首先是简 ...

  6. 巩固javaweb第十三天

    巩固内容: HTML 表格 表格由 <table> 标签来定义.每个表格均有若干行(由 <tr> 标签定义),每行被分割为若干单元格(由 <td> 标签定义).字母 ...

  7. Go知识盲区--闭包

    1. 引言 关于闭包的说明,曾在很多篇幅中都有过一些说明,包括Go基础--函数2, go 函数进阶,异常与错误 都有所提到, 但是会发现,好像原理(理论)都懂,但是就是不知道如何使用,或者在看到一些源 ...

  8. db9串口接头的定义

    这个接头都是以公头为准,所有接头还是以公头去记. RS-232端(DB9公头/针型)引脚定义 2: RXD 3:TXD 5:GND 1/4/6:内部相链接 7/8   :内部相链接 1.RS-232端 ...

  9. oracle 预安装命令

     yum install oracle-rdbms-server-11gR2-preinstall-1.0-6.el6 

  10. Properties类继承HashTable类,一般用来给程序配置属性文件。

    package com.itcast.demo04.Prop;import jdk.internal.util.xml.impl.ReaderUTF8;import sun.nio.cs.UTF_32 ...