There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up (u), down (d), left (l) or right (r), but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls on to the hole.

Given the ball position, the hole position and the maze, find out how the ball could drop into the hole by moving the shortest distance. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the hole (included). Output the moving directions by using 'u', 'd', 'l' and 'r'. Since there could be several different shortest ways, you should output the lexicographically smallest way. If the ball cannot reach the hole, output "impossible".

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 ball and the hole coordinates are represented by row and column indexes.

Example 1

Input 1: a maze represented by a 2D array

0 0 0 0 0
1 1 0 0 1
0 0 0 0 0
0 1 0 0 1
0 1 0 0 0 Input 2: ball coordinate (rowBall, colBall) = (4, 3)
Input 3: hole coordinate (rowHole, colHole) = (0, 1) Output: "lul"
Explanation: There are two shortest ways for the ball to drop into the hole.
The first way is left -> up -> left, represented by "lul".
The second way is up -> left, represented by 'ul'.
Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul".

Example 2

Input 1: a maze represented by a 2D array

0 0 0 0 0
1 1 0 0 1
0 0 0 0 0
0 1 0 0 1
0 1 0 0 0 Input 2: ball coordinate (rowBall, colBall) = (4, 3)
Input 3: hole coordinate (rowHole, colHole) = (3, 0)
Output: "impossible"
Explanation: The ball cannot reach the hole.

Note:

  1. There is only one ball and one hole in the maze.
  2. Both the ball and hole 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 the width and the height of the maze won't exceed 30.

490. The Maze 和 505. The Maze II 迷宫 II 的变形,在二维空间中放了洞,用u, r, d, l 这四个字母来分别表示上右下左,求让球掉入洞中的最小移动距离的移动方向字符串。在步数相等的情况下,返回按字母排序最小的答案。

解法1: BFS

解法2: DFS

Java:BFS,时间复杂度O(m * n * Max(m,n)),空间复杂度O(mn)

class Solution {
class Point {
int row, col, dist; public Point(int row, int col, int dist) {
this.row = row;
this.col = col;
this.dist = dist;
}
} public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
if (maze == null || maze.length == 0) {
return "";
} int m = maze.length, n = maze[0].length;
int[][] distance = new int[m][n]; for (int i = 0; i < m; i++) {
Arrays.fill(distance[i], Integer.MAX_VALUE);
} distance[ball[0]][ball[1]] = 0;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
String[] ways = {"u", "d", "l", "r"}; Map<Integer, String> map = new HashMap<>(); Queue<Point> queue = new LinkedList<>();
queue.add(new Point(ball[0], ball[1], 0)); findShortestWayByBFS(maze, queue, map, distance, hole, ways, directions); return map.containsKey(hole[0] * n + hole[1]) ? map.get(hole[0] * n + hole[1]) : "impossible";
} public void findShortestWayByBFS(int[][] maze, Queue<Point> queue, Map<Integer, String> map, int[][] distance, int[] hole, String[] ways, int[][] directions) {
int n = maze[0].length; while (!queue.isEmpty()) {
Point curPoint = queue.remove(); for (int i = 0; i < 4; i++) {
int row = curPoint.row, col = curPoint.col, dist = curPoint.dist;
String path = map.getOrDefault(row * n + col, ""); while (isValid(row, col, maze, hole)) {
row += directions[i][0];
col += directions[i][1];
++dist;
} if (row != hole[0] || col != hole[1]) {
row -= directions[i][0];
col -= directions[i][1];
--dist;
} path += ways[i]; if (dist < distance[row][col]) {
distance[row][col] = dist;
map.put(row * n + col, path);
queue.add(new Point(row, col, dist));
}
else if (dist == distance[row][col] && path.compareTo(map.getOrDefault(row * n + col, "")) < 0) {
map.put(row * n + col, path);
queue.add(new Point(row, col, dist));
}
}
}
} public boolean isValid(int row, int col, int[][] maze, int[] hole) {
return row >= 0 && row < maze.length && col >= 0 && col < maze[0].length && maze[row][col] == 0 && (row != hole[0] || col != hole[1]);
}
}  

Java:

public class Solution {
public String findShortestWay(int[][] maze, int[] ball, int[] hole) {
Queue<Point> queue = new LinkedList<>();
int row = maze.length;
int col = maze[0].length;
Point[][] points = new Point[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
Point point = new Point(i, j);
points[i][j] = point;
if (i == hole[0] && j == hole[1]) {
point.path = "impossible";
}
}
}
int[] dirX = {0, -1, 1, 0}; // d, l, r, u
int[] dirY = {1, 0, 0, -1};
String[] dir = {"d", "l", "r", "u"};
Point startPoint = points[ball[0]][ball[1]];
startPoint.dis = 0;
queue.add(startPoint);
while (!queue.isEmpty()) {
Point point = queue.poll();
for (int i = 0; i < 4; i++) {
int x = point.x;
int y = point.y;
int dis = point.dis;
String path = point.path;
boolean inHole = false;
while (x >= 0 && x < row && y >= 0 && y < col && maze[x][y] == 0) {
x += dirX[i];
y += dirY[i];
dis++;
if (x == hole[0] && y == hole[1]) {
inHole = true;
break;
}
}
if (!inHole) {
x -= dirX[i];
y -= dirY[i];
dis--;
}
Point newPoint = points[x][y];
if (newPoint.dis > dis) {
newPoint.dis = dis;
newPoint.path = String.join("", point.path, dir[i]);
if (!inHole) {
queue.add(newPoint);
}
} else if (newPoint.dis == dis) {
boolean updated = false;
String newPath = String.join("", point.path, dir[i]);
for (int k = 0; k < newPoint.path.length() && k < newPath.length(); k++) {
if (newPoint.path.charAt(k) > newPath.charAt(k)) {
updated = true;
newPoint.path = newPath;
break;
}
}
if (!updated && newPoint.path.length() > newPath.length()) {
newPoint.path = newPath;
}
}
}
}
return points[hole[0]][hole[1]].path;
}
}
class Point {
int x;
int y;
String path;
int dis;
public Point(int x, int y) {
this.x = x;
this.y = y;
this.path = "";
this.dis = Integer.MAX_VALUE;
}
}  

C++:

class Solution {
public:
string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
int m = maze.size(), n = maze[0].size();
vector<vector<int>> dists(m, vector<int>(n, INT_MAX));
vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
vector<char> way{'l','u','r','d'};
queue<pair<int, int>> q;
unordered_map<int, string> u;
dists[ball[0]][ball[1]] = 0;
q.push({ball[0], ball[1]});
while (!q.empty()) {
auto t = q.front(); q.pop();
for (int i = 0; i < 4; ++i) {
int x = t.first, y = t.second, dist = dists[x][y];
string path = u[x * n + y];
while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0 && (x != hole[0] || y != hole[1])) {
x += dirs[i][0]; y += dirs[i][1]; ++dist;
}
if (x != hole[0] || y != hole[1]) {
x -= dirs[i][0]; y -= dirs[i][1]; --dist;
}
path.push_back(way[i]);
if (dists[x][y] > dist) {
dists[x][y] = dist;
u[x * n + y] = path;
if (x != hole[0] || y != hole[1]) q.push({x, y});
} else if (dists[x][y] == dist && u[x * n + y].compare(path) > 0) {
u[x * n + y] = path;
if (x != hole[0] || y != hole[1]) q.push({x, y});
}
}
}
string res = u[hole[0] * n + hole[1]];
return res.empty() ? "impossible" : res;
}
};

C++: DFS

class Solution {
public:
vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
vector<char> way{'l','u','r','d'};
string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
int m = maze.size(), n = maze[0].size();
vector<vector<int>> dists(m, vector<int>(n, INT_MAX));
unordered_map<int, string> u;
dists[ball[0]][ball[1]] = 0;
helper(maze, ball[0], ball[1], hole, dists, u);
string res = u[hole[0] * n + hole[1]];
return res.empty() ? "impossible" : res;
}
void helper(vector<vector<int>>& maze, int i, int j, vector<int>& hole, vector<vector<int>>& dists, unordered_map<int, string>& u) {
if (i == hole[0] && j == hole[1]) return;
int m = maze.size(), n = maze[0].size();
for (int k = 0; k < 4; ++k) {
int x = i, y = j, dist = dists[x][y];
string path = u[x * n + y];
while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0 && (x != hole[0] || y != hole[1])) {
x += dirs[k][0]; y += dirs[k][1]; ++dist;
}
if (x != hole[0] || y != hole[1]) {
x -= dirs[k][0]; y -= dirs[k][1]; --dist;
}
path.push_back(way[k]);
if (dists[x][y] > dist) {
dists[x][y] = dist;
u[x * n + y] = path;
helper(maze, x, y, hole, dists, u);
} else if (dists[x][y] == dist && u[x * n + y].compare(path) > 0) {
u[x * n + y] = path;
helper(maze, x, y, hole, dists, u);
}
}
}
};

  

  

类似题目:

[LeetCode] 490. The Maze 迷宫

[LeetCode] 505. The Maze II 迷宫 II

All LeetCode Questions List 题目汇总

[LeetCode] 499. The Maze III 迷宫 III的更多相关文章

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

  2. LeetCode 499. The Maze III

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

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

  4. 【LeetCode】556. Next Greater Element III 解题报告(Python)

    [LeetCode]556. Next Greater Element III 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人 ...

  5. 3299: [USACO2011 Open]Corn Maze玉米迷宫

    3299: [USACO2011 Open]Corn Maze玉米迷宫 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 137  Solved: 59[ ...

  6. [LeetCode] The Maze III 迷宫之三

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...

  7. LC 499. The Maze III 【lock,hard】

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...

  8. [LeetCode] The Maze II 迷宫之二

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...

  9. [LeetCode] 490. The Maze 迷宫

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...

随机推荐

  1. uiautomator2+python自动化测试1-环境准备

    前言 uiautomator是Google提供的用来做安卓自动化测试的一个Java库.功能很强,可以对第三方App进行测试,获取屏幕上任意一个APP的任意一个控件属性,并对其进行任意操作,但有两个缺点 ...

  2. 基于Centos7+Flask+Nginx+uWSGI+Python3的服务器网页搭建教程

    之前完成了贴吧签到系统的搭建,笔者想将这个功能分享给更多人使用,所以尝试搭建了一个网页,一路遇到了很多问题,最终解决了,记录下过程分享给大家 首先安装 uWSGI ,和 Nginx 配套使用,具体用途 ...

  3. Xamarin开发及学习资源

    入行文章指引 移动开发下Xamarin VS PhoneGap 跨平台开发 许多企业希望能够通过开发移动应用程序,来提升企业业务水平,开发原生App时往往又缺少专业的Objective C 或 Jav ...

  4. 设置make为内部命令

    在Windows中下载Dev-cpp,配置环境变量,在MinGW64\bin下的mingw32-make.exe改名为make.exe,即可在命令行中使用make命令.

  5. 56、Spark Streaming: transform以及实时黑名单过滤案例实战

    一.transform以及实时黑名单过滤案例实战 1.概述 transform操作,应用在DStream上时,可以用于执行任意的RDD到RDD的转换操作.它可以用于实现,DStream API中所没有 ...

  6. 去参加了十四届D2前端大会~

    朋友喊我去一起去d2,原来一直在加班,没有想去的动力,后来业务上线,幸运的入手了别人转的一张票(也不便宜啊)- 讲了五个挑战 端侧渲染体系的重塑,从PC时代到无线时代,再到未来的IOT时代,在渲染方面 ...

  7. redis状态详解

    redis查看状态信息 info all|default Info 指定项 server服务器信息 redis_version : Redis 服务器版本 redis_git_sha1 : Git S ...

  8. 帝国cms7.5整合百度编辑器ueditor教程

    1.根据自己使用的帝国cms版本编码下载对应的ueditor版本 下载地址 http://ueditor.baidu.com/website/download.html#ueditor 2.解压附件, ...

  9. CSS背景和精灵图

    如何设置背景图片? 1.在CSS中有个叫做background-image:url():的属性,就是专门用于设置背景图片的. 2.注意点: 1)图片的地址必须放在url()中,图片的地址可以是本地的地 ...

  10. qemu-img convert -c disk /var/lib/nova/instances/_base/94a107318b54108fc8e76fff21a86d7c390a20bf -O qcow2 hebin.qcow2