1926. Nearest Exit from Entrance in Maze
2D to 1D value
T:O(mn)
S:O(mn)
```java
class Solution {
class Step {
int x;
int y;
int level;
Step(int x, int y, int level) {
this.x = x;
this.y = y;
this.level = level;
}
}
private static final int[][] DIRS = {{0,1}, {1,0}, {0,-1}, {-1,0}};
public int nearestExit(char[][] maze, int[] entrance) {
int m = maze.length;
int n = maze[0].length;
Set<Integer> exit = new HashSet<>();
for (int i = 0; i < m; i++) {
if (maze[i][0] == '.') {
exit.add(i*m);
}
if (maze[i][n-1] == '.') {
exit.add(i*m + n-1);
}
}
for (int j = 0; j < n; j++) {
if (maze[0][j] == '.') {
exit.add(j);
}
if (maze[m-1][j] == '.') {
exit.add((m-1)*m + j);
}
}
exit.remove(entrance[0]*m + entrance[1]);
if (exit.size() == 0) {
return -1;
}
Queue<Step> queue = new LinkedList<>();
queue.offer(new Step(entrance[0], entrance[1], 0));
boolean[][] visited = new boolean[m][n];
while (!queue.isEmpty()) {
Step cur = queue.poll();
if (visited[cur.x][cur.y]) {
continue;
}
visited[cur.x][cur.y] = true;
if (exit.contains(cur.x*m + cur.y)) {
return cur.level;
}
for (int[] dir : DIRS) {
int x = cur.x + dir[0];
int y = cur.y + dir[1];
if (x < 0 || x >= m || y < 0 || y >= n || maze[x][y] == '+') {
continue;
}
queue.offer(new Step(x, y, cur.level+1));
}
}
return -1;
}
}
```
Last updated