Simple BFS (Java) | 7ms | Beats 100%
The idea is to perform simple breadth first search using a queue. While adding new elements, we perform a simple operation to check if the element being offered
The idea is to perform simple breadth first search using a queue. While adding new elements, we perform a simple operation to check if the element being offered exists in first or last row **OR** first or last column.\n\n\n```\nclass Solution {\n    public int nearestExit(char[][] maze, int[] entrance) {\n        int rows = maze.length, cols = maze[0].length, queueSize;\n        Queue<int[]> queue = new LinkedList<>();\n        boolean[][] visited = new boolean[rows][cols];\n        int[] curr;\n        int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n        int x, y, steps = 0;\n        \n        queue.offer(entrance);\n        visited[entrance[0]][entrance[1]] = true;\n        \n        while (!queue.isEmpty()) {\n            queueSize = queue.size();\n            steps++;\n            \n            for (int i=0;i<queueSize;i++) {\n                curr = queue.poll();\n                \n                for (int[] dir: dirs) {\n                    x = dir[0]+curr[0];                    \n                    y = dir[1]+curr[1];\n                    \n                    if (x<0||x>=rows||y<0||y>=cols) continue;\n                    if (visited[x][y] || maze[x][y] == \'+\') continue;\n                    \n\t\t\t\t\t// check if we have reached boundary\n                    if (x==0||x==rows-1||y==0||y==cols-1) return steps;\n                    \n                    queue.offer(new int[]{x, y});\n                    visited[x][y] = true;\n                }\n            }\n        }\n        \n        return -1;\n    }\n}\n```\n\nSpace - O(mn)\nTime - O(mn)\nwhere m = number of rows and n = number of columns\n
['Breadth-First Search', 'Queue', 'Java']