Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/499.html
499. The Maze III
Level
Hard
Description
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:
- There is only one ball and one hole in the maze.
- Both the ball and hole 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 the width and the height of the maze won’t exceed 30.
Solution
Initialize the distances to INFINITY
for all positions except start
, which has distance 0. Initialize the paths for all positions to null
. Since the shortest distance is required, use priority queue during the search. Starting from start
, each time obtain all possible positions the ball can reach and stop at, update the shortest distances and paths for such positions, and then do further search from the new positions. If the ball can reach hole
, update the shortest distance and the lexicographically smallest path for hole
. After all possible positions are visited, the shortest distances possible and corresponding paths are also obtained. Return the path to reach hole
, which is the string of directions if hole
can be reached, or “impossible” otherwise.
-
class Solution { public String findShortestWay(int[][] maze, int[] ball, int[] hole) { final int WALL = 1; int rows = maze.length, columns = maze[0].length; int[][] distances = new int[rows][columns]; String[][] paths = new String[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (maze[i][j] == WALL) distances[i][j] = -1; else distances[i][j] = Integer.MAX_VALUE; } } int shortestDistance = Integer.MAX_VALUE; String minPath = "impossible"; int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int directionsCount = directions.length; String[] directionsPath = {"u", "d", "l", "r"}; PriorityQueue<PositionDistancePath> priorityQueue = new PriorityQueue<PositionDistancePath>(); distances[ball[0]][ball[1]] = 0; paths[ball[0]][ball[1]] = ""; priorityQueue.offer(new PositionDistancePath(ball[0], ball[1], 0, "")); while (!priorityQueue.isEmpty()) { PositionDistancePath positionDistancePath = priorityQueue.poll(); int row = positionDistancePath.getRow(), column = positionDistancePath.getColumn(), distance = positionDistancePath.getDistance(); String path = positionDistancePath.getPath(); if (distance > shortestDistance) break; for (int i = 0; i < directionsCount; i++) { int[] direction = directions[i]; int deltaRow = direction[0], deltaColumn = direction[1]; String directionPath = directionsPath[i]; String newPath = path + directionPath; int moveCount = 0; int stopRow = row, stopColumn = column; int curRow = row + deltaRow, curColumn = column + deltaColumn; while (curRow >= 0 && curRow < rows && curColumn >= 0 && curColumn < columns && maze[curRow][curColumn] != WALL) { moveCount++; stopRow = curRow; stopColumn = curColumn; if (stopRow == hole[0] && stopColumn == hole[1]) { int newDistance = distance + moveCount; if (minPath.equals("impossible") || newDistance < shortestDistance || newDistance == shortestDistance && newPath.compareTo(minPath) < 0) { distances[hole[0]][hole[1]] = newDistance; paths[hole[0]][hole[1]] = newPath; shortestDistance = Math.min(shortestDistance, newDistance); minPath = newPath; } break; } curRow = stopRow + deltaRow; curColumn = stopColumn + deltaColumn; } int newDistance = distance + moveCount; if (newDistance < distances[stopRow][stopColumn] || (newDistance == distances[stopRow][stopColumn] && (paths[stopRow][stopColumn] == null || newPath.compareTo(paths[stopRow][stopColumn]) < 0))) { distances[stopRow][stopColumn] = newDistance; paths[stopRow][stopColumn] = newPath; priorityQueue.offer(new PositionDistancePath(stopRow, stopColumn, newDistance, newPath)); } } } return minPath; } } class PositionDistancePath implements Comparable<PositionDistancePath> { private int row; private int column; private int distance; private String path = ""; public PositionDistancePath() { } public PositionDistancePath(int row, int column, int distance, String path) { this.row = row; this.column = column; this.distance = distance; this.path = path; } public int getRow() { return row; } public int getColumn() { return column; } public int getDistance() { return distance; } public String getPath() { return path; } public int compareTo(PositionDistancePath positionDistance2) { if (distance != positionDistance2.distance) return distance - positionDistance2.distance; return path.compareTo(positionDistance2.path); } }
-
// OJ: https://leetcode.com/problems/the-maze-iii/ // Time: O((MN)^2log(MN)) // Space: O((MN)^2) class Solution { typedef tuple<int, string, int, int> item; // distance, instruction, x, y public: string findShortestWay(vector<vector<int>>& A, vector<int>& ball, vector<int>& hole) { int M = A.size(), N = A[0].size(), dirs[4][2] = { {1,0},{0,-1},{0,1},{-1,0} }; string chars = "dlru"; vector<vector<int>> dist(M, vector<int>(N, INT_MAX)); dist[ball[0]][ball[1]] = 0; vector<vector<string>> ins(M, vector<string>(N)); priority_queue<item, vector<item>, greater<>> pq; pq.push({0, "", ball[0], ball[1]}); while (pq.size()) { auto [cost, inst, x, y] = pq.top(); pq.pop(); if (x == hole[0] && y == hole[1]) return inst; if (cost > dist[x][y]) continue; for (int i = 0; i < 4; ++i) { auto [dx, dy] = dirs[i]; int a = x + dx, b = y + dy, step = 1; while (a >= 0 && a < M && b >= 0 && b < N && A[a][b] == 0 && (a != hole[0] || b != hole[1])) a += dx, b += dy, ++step; if (a != hole[0] || b != hole[1]) a -= dx, b -= dy, --step; if (a == x && b == y) continue; int newCost = cost + step; auto newInst = inst + chars[i]; if (dist[a][b] > newCost) { dist[a][b] = newCost; ins[a][b] = newInst; pq.push({newCost, newInst, a, b}); } else if (dist[a][b] == newCost && (ins[a][b].empty() || newInst < ins[a][b])) { ins[a][b] = newInst; pq.push({newCost, newInst, a, b}); } } } return "impossible"; } };
-
class Solution: def findShortestWay( self, maze: List[List[int]], ball: List[int], hole: List[int] ) -> str: m, n = len(maze), len(maze[0]) r, c = ball rh, ch = hole q = deque([(r, c)]) dist = [[inf] * n for _ in range(m)] dist[r][c] = 0 path = [[None] * n for _ in range(m)] path[r][c] = '' while q: i, j = q.popleft() for a, b, d in [(-1, 0, 'u'), (1, 0, 'd'), (0, -1, 'l'), (0, 1, 'r')]: x, y, step = i, j, dist[i][j] while ( 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0 and (x != rh or y != ch) ): x, y = x + a, y + b step += 1 if dist[x][y] > step or ( dist[x][y] == step and path[i][j] + d < path[x][y] ): dist[x][y] = step path[x][y] = path[i][j] + d if x != rh or y != ch: q.append((x, y)) return path[rh][ch] or 'impossible' ############ import heapq class Solution(object): def findShortestWay(self, maze, ball, hole): """ :type maze: List[List[int]] :type ball: List[int] :type hole: List[int] :rtype: str """ def next(curr, maze): height = len(maze) width = len(maze[0]) directions = [(-1, 0, "u"), (1, 0, "d"), (0, -1, "l"), (0, 1, "r")] for di, dj, mark in directions: dist = 0 i, j = curr while 0 <= i + di < height and 0 <= j + dj < width and maze[i + di][j + dj] != 1: i += di j += dj dist += 1 if (i, j) == hole: break yield (i, j), mark, dist heap = [(0, "", tuple(ball))] visited = set() hole = tuple(hole) while heap: dist, word, curr = heapq.heappop(heap) if curr in visited: continue visited |= {curr} if curr == hole: return word for pos, mark, incDist in next(curr, maze): heapq.heappush(heap, (dist + incDist, word + mark, pos)) return "impossible"
-
import "math" func findShortestWay(maze [][]int, ball []int, hole []int) string { m, n := len(maze), len(maze[0]) r, c := ball[0], ball[1] rh, ch := hole[0], hole[1] q := [][]int{[]int{r, c} } dist := make([][]int, m) path := make([][]string, m) for i := range dist { dist[i] = make([]int, n) path[i] = make([]string, n) for j := range dist[i] { dist[i][j] = math.MaxInt32 path[i][j] = "" } } dist[r][c] = 0 dirs := map[string][]int{"u": {-1, 0}, "d": {1, 0}, "l": {0, -1}, "r": {0, 1} } for len(q) > 0 { p := q[0] q = q[1:] i, j := p[0], p[1] for d, dir := range dirs { a, b := dir[0], dir[1] x, y := i, j step := dist[i][j] for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 && (x != rh || y != ch) { x += a y += b step++ } if dist[x][y] > step || (dist[x][y] == step && (path[i][j]+d) < path[x][y]) { dist[x][y] = step path[x][y] = path[i][j] + d if x != rh || y != ch { q = append(q, []int{x, y}) } } } } if path[rh][ch] == "" { return "impossible" } return path[rh][ch] }