forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1926.java
35 lines (33 loc) · 1.47 KB
/
_1926.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.fishercoder.solutions;
import java.util.LinkedList;
import java.util.Queue;
public class _1926 {
public static class Solution1 {
public int nearestExit(char[][] maze, int[] entrance) {
int m = maze.length;
int n = maze[0].length;
int[] directions = new int[]{0, 1, 0, -1, 0};
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{entrance[0], entrance[1], 0});
boolean[][] visited = new boolean[m][n];
visited[entrance[0]][entrance[1]] = true;
int shortestSteps = m * n;
while (!queue.isEmpty()) {
int[] curr = queue.poll();
for (int i = 0; i < directions.length - 1; i++) {
int nextX = curr[0] + directions[i];
int nextY = curr[1] + directions[i + 1];
if (nextX >= 0 && nextX < m && nextY >= 0 && nextY < n && maze[nextX][nextY] == '.' && !visited[nextX][nextY]) {
visited[nextX][nextY] = true;
if (nextX == 0 || nextX == m - 1 || nextY == 0 || nextY == n - 1) {
shortestSteps = Math.min(shortestSteps, curr[2] + 1);
} else {
queue.offer(new int[]{nextX, nextY, curr[2] + 1});
}
}
}
}
return shortestSteps == m * n ? -1 : shortestSteps;
}
}
}