Simple BFS using Java | O(m*n) time and O(1) space.
\n# Approach\n Describe your approach to solving the problem. \nSimple BFS using a Queue Data Structure.\n\n# Complexity\n- Time complexity: O(m * n)\n Add your
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSimple **BFS** using a Queue Data Structure.\n\n# Complexity\n- Time complexity: O(m * n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n    public int nearestExit(char[][] maze, int[] entrance) {\n\n        int m = maze.length;\n        int n = maze[0].length;\n\n        int[] dx = {1, -1, 0, 0};\n        int[] dy = {0, 0, -1, 1};\n        Deque<int[]> queue = new ArrayDeque<>();\n\n        queue.add(new int[] {entrance[0], entrance[1], 0});\n        maze[entrance[0]][entrance[1]] = \'+\';\n\n        while(! queue.isEmpty()) {\n            int[] curr = queue.pollFirst();\n            int r = curr[0];\n            int c = curr[1];\n            int dist = curr[2];\n\n            for(int i = 0; i < 4; i++) {\n                int x = r + dx[i];\n                int y = c + dy[i];\n\n                if(x == -1 || y == -1 || x == m || y == n) continue;\n                if(maze[x][y] == \'+\') continue;\n                if(x == 0 || y == 0 || x == m - 1 || y == n - 1) return dist + 1;\n                maze[x][y] = \'+\';\n                queue.add(new int[] {x, y, dist + 1});\n            }\n        }\n        return -1;\n    }\n}\n```
['Breadth-First Search', 'Java']