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