JAVA || Why BFS || Simple Steps
Steps to follow:\n1. Whenever you come accross a question asking for the shortest distance, Go for BFS as in DFS the first route may not be the shortest one but
Steps to follow:\n1. Whenever you come accross a question asking for the shortest distance, **Go for BFS** as in DFS the first route may not be the shortest one but BFS assures the shortest path.\n2. We need to take a **Queue and a Visited Array**.\n3. Queue is to add all the nodes breath wise at each iteration\n4. Visited array to mark the visited value as true as soon as we add it into the bfs queue.\n5. To count the number of steps , we will take a steps variable which will be incremented as we pass through **each level in the BFS traversal**.\n5. Only those nodes to be added into the Queue which are true to all our conditions.\n6. While adding do check if the current node is at the boundary or not.\n7. If yes , number of levels passed  so far is your answer.\n\n```\nclass Solution {\n    public int nearestExit(char[][] maze, int[] ent) {\n        \n        // dir array to go in all 4 directions\n        int[][] dir = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};\n        int xVal = ent[0];\n        int yVal = ent[1];\n        \n        int n = maze.length;\n        int m = maze[0].length;\n        \n        Queue<int[]> q = new LinkedList<>();\n        // visted array to restrict control to go to already visited node\n        boolean vis[][] = new boolean[n][m];\n        \n        q.add(ent);\n        // mark the visited value as true as soon as we add it into the bfs queue.\n        vis[xVal][yVal] = true;\n        int steps = 0;\n        \n        while(!q.isEmpty())\n        {\n            int size = q.size();\n            steps++;\n            for(int i=0;i<size;i++)\n            {\n                int[] node = q.poll();\n                for(int k=0;k<dir.length;k++)\n                {\n                    int x = node[0]+dir[k][0];\n                    int y = node[1]+dir[k][1];\n                    // check for all conditions\n                    if(x>=0 && x<n && y >=0 && y<m && vis[x][y] == false && maze[x][y] == \'.\')\n                    {\n                        q.add(new int[]{x,y});\n                        vis[x][y] = true;\n                        \n                        // if the control is on the boundary just return.\n                        if(x == 0 || y == 0 || x ==n-1 || y== m-1)\n                            return steps;\n                    }\n                }\n            }\n        \n        }\n        \n        return -1;\n    }\n}\n```
['Breadth-First Search', 'Java']