Skip to content

Commit ae399d8

Browse files
authored
Create Nearest Exit from Entrance in Maze.java
1 parent 1812e49 commit ae399d8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
3+
4+
public int nearestExit(char[][] maze, int[] entrance) {
5+
int rows = maze.length;
6+
int cols = maze[0].length;
7+
Queue<int[]> queue = new LinkedList<>();
8+
boolean[][] visited = new boolean[rows][cols];
9+
int entranceRow = entrance[0];
10+
int entranceCol = entrance[1];
11+
queue.add(new int[]{entranceRow, entranceCol});
12+
visited[entranceRow][entranceCol] = true;
13+
int steps = 0;
14+
while (!queue.isEmpty()) {
15+
int size = queue.size();
16+
while (size-- > 0) {
17+
int[] removed = queue.remove();
18+
int row = removed[0];
19+
int col = removed[1];
20+
if (!(row == entranceRow && col == entranceCol) && isExit(row, col, rows, cols)) {
21+
return steps;
22+
}
23+
for (int[] dir : DIRS) {
24+
int newRow = row + dir[0];
25+
int newCol = col + dir[1];
26+
if (newRow >= 0 &&
27+
newCol >= 0 &&
28+
newRow < rows &&
29+
newCol < cols &&
30+
!visited[newRow][newCol] &&
31+
maze[newRow][newCol] != '+') {
32+
queue.add(new int[]{newRow, newCol});
33+
visited[newRow][newCol] = true;
34+
}
35+
}
36+
}
37+
steps++;
38+
}
39+
return -1;
40+
}
41+
42+
private boolean isExit(int row, int col, int rows, int cols) {
43+
return (row + 1 == rows) || (row - 1 == -1) || (col + 1 == cols) || (col - 1 == -1);
44+
}
45+
}

0 commit comments

Comments
 (0)