1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00

java: add «1926. Nearest Exit from Enterance in Maze»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-06 19:15:33 +02:00
parent edafb98470
commit be62180317
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,53 @@
import java.util.ArrayDeque;
class Solution {
private static final int[][] DIRECTIONS =
new int[][] {
new int[] {0, 1},
new int[] {0, -1},
new int[] {1, 0},
new int[] {-1, 0},
};
private record Cell(int distance, int y, int x) {
public boolean onEdge(int width, int height) {
return y == 0 || y == height - 1 || x == 0 || x == width - 1;
}
public boolean inBounds(int width, int height) {
return y >= 0 && y < height && x >= 0 && x < width;
}
}
public int nearestExit(char[][] maze, int[] entrance) {
int width = maze[0].length, height = maze.length;
var visited = new boolean[height][width];
var q = new ArrayDeque<Cell>();
q.offer(new Cell(0, entrance[0], entrance[1]));
visited[entrance[0]][entrance[1]] = true;
while (!q.isEmpty()) {
var c = q.poll();
if (c.onEdge(width, height) && c.distance() > 0) {
return c.distance();
}
for (var d : DIRECTIONS) {
int dy = d[0], dx = d[1];
var n = new Cell(c.distance() + 1, c.y() + dy, c.x() + dx);
if (!n.inBounds(width, height) || maze[n.y()][n.x()] != '.' || visited[n.y()][n.x()]) {
continue;
}
q.offer(n);
visited[n.y()][n.x()] = true;
}
}
return -1;
}
}