LeetCode 505: The Maze II Solution
Master LeetCode problem 505 (The Maze II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
505. The Maze II
Problem Explanation
Explanation:
The problem requires finding the shortest path in a maze from the start to the destination. The maze is represented as a 2D array where 0 represents an empty space and 1 represents a wall. The ball can roll in four directions (up, down, left, right) until it hits a wall. Once it hits a wall, it will stop at the previous position. The distance between two positions is defined by the number of steps taken.
To solve this problem, we can use Dijkstra's algorithm with a priority queue. We start from the start position and explore all possible directions the ball can roll in. For each direction, we calculate the distance from the start position and add it to the priority queue. We continue this process until we reach the destination position or explore all possible paths. :
Solution Code
import java.util.*;
class Solution {
public int shortestDistance(int[][] maze, int[] start, int[] destination) {
int m = maze.length, n = maze[0].length;
int[][] distance = new int[m][n];
for (int[] row : distance) {
Arrays.fill(row, Integer.MAX_VALUE);
}
int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
Queue<int[]> queue = new PriorityQueue<>((a, b) -> a[2] - b[2]);
queue.offer(new int[]{start[0], start[1], 0});
distance[start[0]][start[1]] = 0;
while (!queue.isEmpty()) {
int[] curr = queue.poll();
if (curr[0] == destination[0] && curr[1] == destination[1]) {
return distance[curr[0]][curr[1]];
}
for (int[] dir : dirs) {
int x = curr[0], y = curr[1], dist = curr[2];
while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0) {
x += dir[0];
y += dir[1];
dist++;
}
x -= dir[0];
y -= dir[1];
dist--;
if (dist < distance[x][y]) {
distance[x][y] = dist;
queue.offer(new int[]{x, y, dist});
}
}
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 505 (The Maze II)?
This page provides optimized solutions for LeetCode problem 505 (The Maze II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 505 (The Maze II)?
The time complexity for LeetCode 505 (The Maze II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 505 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 505 in Java, C++, or Python.