Nearest Exit from Entrance in Maze LeetCode solution in Java

1
class Solution {
2
public int nearestExit(char[][] maze, int[] entrance) {
3
int rows = maze.length, cols = maze[0].length, queueSize;
4
Queue<int[]> queue = new LinkedList<>();
5
boolean[][] visited = new boolean[rows][cols];
6
int[] curr;
7
int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
8
int x, y, steps = 0;
9

10
queue.offer(entrance);
11
visited[entrance[0]][entrance[1]] = true;
12

13
while (!queue.isEmpty()) {
14
queueSize = queue.size();
15
steps++;
16

17
for (int i = 0; i < queueSize; i++) {
18
curr = queue.poll();
19

20
for (int[] dir : dirs) {
21
x = dir[0] + curr[0];
22
y = dir[1] + curr[1];
23

24
if (x < 0 || x >= rows || y < 0 || y >= cols) continue;
25
if (visited[x][y] || maze[x][y] == '+') continue;
26

27
// check if we have reached boundary
28
if (x == 0 || x == rows - 1 || y == 0 || y == cols - 1) return steps;
29

30
queue.offer(new int[] {x, y});
31
visited[x][y] = true;
32
}
33
}
34
}
35

36
return -1;
37
}
38
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0