LeetCode 505: The Maze II
Problem Description
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. :
Solutions
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;
}
}
Related LeetCode Problems
Loading editor...