SOLVED-JAVA BFS
\nclass Solution {\n    public int nearestExit(char[][] maze, int[] entrance) {\n        int[][] directions = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};\n        i
```\nclass Solution {\n    public int nearestExit(char[][] maze, int[] entrance) {\n        int[][] directions = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};\n        int m = maze.length;\n        int n = maze[0].length;\n      \n        int count =0;\n        int result =Integer.MAX_VALUE;\n        Queue<int[]> queue = new LinkedList<>();\n        boolean[][] visited = new boolean[m][n];\n        queue.offer(entrance);\n        while(!queue.isEmpty()){\n            int size = queue.size();\n            count++;\n            for(int i =0; i<size;i++){\n                int[] temp = queue.poll();\n                visited[temp[0]][temp[1]]=true;\n           \n                for(int[] dir:directions){\n                    int x = temp[0]+dir[0];\n                    int y = temp[1]+dir[1];\n                    if(x>=0&&x<m &&y>=0&&y<n&&visited[x][y]==false&&maze[x][y]==\'.\'){\n                        queue.offer(new int[]{x,y});\n                        if(x==0||y==0||x==m-1||y==n-1){\n                            return count;\n                        }\n                   }\n                }\n            }            \n        }\n        return -1;             \n        \n    }\n}\n```\n\nSo weird... I got accept after one change - I marked visited[i][j] every time poll it from the queue before, and now change it to mark it after offer it to queue.  as following. Anyone can explain it? Thanks!\n```\nclass Solution {\n    public int nearestExit(char[][] maze, int[] entrance) {\n        int[][] directions = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};\n        int m = maze.length;\n        int n = maze[0].length;\n      \n        int count =0;\n        Queue<int[]> queue = new LinkedList<>();\n        boolean[][] visited = new boolean[m][n];\n        visited[entrance[0]][entrance[1]]=true;\n        queue.offer(entrance);\n        while(!queue.isEmpty()){\n            int size = queue.size();\n            count++;\n            for(int i =0; i<size;i++){\n                int[] temp = queue.poll();\n                \n           \n                for(int[] dir:directions){\n                    int x = temp[0]+dir[0];\n                    int y = temp[1]+dir[1];\n                    if(x>=0&&x<m &&y>=0&&y<n&&visited[x][y]==false&&maze[x][y]==\'.\'){\n                        queue.offer(new int[]{x,y});\n                        if(x==0||y==0||x==m-1||y==n-1){\n                            return count;\n                        }\n                        \n                        visited[x][y]=true;\n                   }\n                }\n            }            \n        }\n        return -1;             \n        \n    }\n}\n```
['Breadth-First Search', 'Java']