question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nearest-exit-from-entrance-in-maze | C++ || BFS || Easy to Understand | c-bfs-easy-to-understand-by-mohakharjani-vnck | \nclass Solution {\npublic:\n vector<int>rowDir = {-1, 1, 0, 0};\n vector<int>colDir = {0, 0, -1, 1};\n bool isAtBorder(vector<vector<char>>&maze, int | mohakharjani | NORMAL | 2022-11-21T00:45:00.606143+00:00 | 2022-11-21T00:45:00.606177+00:00 | 3,108 | false | ```\nclass Solution {\npublic:\n vector<int>rowDir = {-1, 1, 0, 0};\n vector<int>colDir = {0, 0, -1, 1};\n bool isAtBorder(vector<vector<char>>&maze, int row, int col)\n {\n if ((row == 0) || (row == maze.size() - 1)) return true;\n if ((col == 0) || (col == maze[0].size() - 1)) return true;\n return false;\n }\n bool isValidStep(vector<vector<char>>&maze, int& row, int& col)\n {\n int m = maze.size(), n = maze[0].size();\n if (row < 0 || row == m || col < 0 || col == n || maze[row][col] == \'+\') return false;\n else return true;\n }\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) \n {\n queue<pair<int, int>>q;\n q.push({entrance[0], entrance[1]});\n int pathLen = 0;\n maze[entrance[0]][entrance[1]] = \'+\'; //Instead of using a visited matrix, just mark the visited cell as \'+\'\n //\'+\' will mean that it is either a wall or cell that is already visited\n while(!q.empty())\n {\n int size = q.size();\n while(size--)\n {\n int currRow = q.front().first;\n int currCol = q.front().second;\n q.pop();\n\n //================================================================================\n //explores all adjacent cells without writing more code \n for (int dirIdx = 0; dirIdx < 4; dirIdx++) //checking top, bottom, left, right\n {\n int newRow = currRow + rowDir[dirIdx]; //currRow - 1, currRow + 1, currRow + 0, currRow + 0\n int newCol = currCol + colDir[dirIdx]; //currCol + 0, currCol + 0, currCol - 1, currCol + 1\n if (isValidStep(maze, newRow, newCol)) \n {\n maze[newRow][newCol] = \'+\'; //mark as visited and push in queue\n if (isAtBorder(maze, newRow, newCol)) return (pathLen + 1); //BOOM, GOT YOUR TARGET :))\n else q.push({newRow, newCol});\n }\n }\n //====================================================================================\n }\n pathLen++; \n }\n return -1;\n }\n};\n``` | 16 | 2 | ['Breadth-First Search', 'Queue', 'C', 'C++'] | 3 |
nearest-exit-from-entrance-in-maze | DFS Anomaly | dfs-anomaly-by-kesharipiyush24-u414 | I wasted hours debugging my DFS Solution and a lesson learned for life that I will never ever use DFS to find shortest path from now onwards.\n \nCode which is | KeshariPiyush24 | NORMAL | 2021-07-12T07:05:53.723200+00:00 | 2021-07-12T07:08:42.591301+00:00 | 2,100 | false | I wasted hours debugging my DFS Solution and a lesson learned for life that I will never ever use DFS to find shortest path from now onwards.\n \nCode which is finally working:\n```java\nclass Solution {\n int[][] dp = new int[101][101];\n boolean[][] visited = new boolean[101][101];\n int i;\n int j;\n \n public int nearestExit(char[][] maze, int[] entrance) {\n int m = maze.length;\n int n = maze[0].length;\n i = entrance[0];\n j = entrance[1];\n int res = dfs(maze, i, j, m, n);\n return res >= 10001 ? -1 : res;\n }\n \n int dfs(char[][] maze, int row, int col, int m, int n) {\n \n if (row < 0 || row >= m || col < 0 || col >= n || maze[row][col] == \'+\' || visited[row][col]) {\n return 10001;\n } else if (dp[row][col] != 0) {\n return dp[row][col];\n } else if (isExit(row, col, m, n) && !isEntrance(row, col)) {\n return dp[row][col] = 0;\n }\n \n visited[row][col] = true;\n int down = dfs(maze, row + 1, col, m, n);\n int up = dfs(maze, row - 1, col, m, n);\n int right = dfs(maze, row, col + 1, m, n);\n int left = dfs(maze, row, col - 1, m, n);\n visited[row][col] = false;\n \n return dp[row][col] = Math.min(Math.min(up, down), Math.min(left, right)) + 1;\n }\n \n boolean isExit(int row, int col, int m, int n) {\n if (row == 0 || row == m - 1 || col == 0 || col == n - 1) { \n return true;\n } else {\n return false;\n }\n }\n \n boolean isEntrance(int row, int col) {\n if (row == i && col == j) { \n return true;\n } else {\n return false;\n }\n }\n}\n```\n\nBut if I change the order of traversal to child nodes for example:\n```java\n int up = dfs(maze, row - 1, col, m, n);\nint right = dfs(maze, row, col + 1, m, n);\nint down = dfs(maze, row + 1, col, m, n);\nint left = dfs(maze, row, col - 1, m, n);\n```\n**Boom it fails for some of the testcases.**\n\nThings I know about this problem:\n- Unweighted graph\n- Cyclic graph\n- Only One SCC(Strongly Connected Component)\n\nBut can someone give me a proof that why DFS will never work(well I think it was just a luck that all the testcases happend to pass for one particular order but there is no gaurantee that DFS will work in this kind of problem). | 16 | 1 | ['Dynamic Programming', 'Depth-First Search', 'Breadth-First Search', 'Graph', 'Recursion', 'Java'] | 4 |
nearest-exit-from-entrance-in-maze | Python 3 | BFS, Deque, In-place | Explanation | python-3-bfs-deque-in-place-explanation-amt5d | Explanation\n- Use BFS to find shortest/closest\n- Starting from entrance, if you see a . on the boarder and it\'s not the entrance, then that\'s a exit\n- Mark | idontknoooo | NORMAL | 2021-07-10T18:45:20.848463+00:00 | 2021-07-10T18:45:20.848509+00:00 | 1,521 | false | ### Explanation\n- Use `BFS` to find shortest/closest\n- Starting from `entrance`, if you see a `.` on the boarder and it\'s not the entrance, then that\'s a exit\n- Mark visited place as `+` to avoid revisit (also we don\'t need to use a `visisted = set()` here)\n- We pass a 3rd parameter as the `step` we need to reach a certain place. Return this step when exit is found\n- A very similar question to this is [1730. Shortest Path to Get Food](https://leetcode.com/problems/shortest-path-to-get-food/)\n- Time: `O(m*n)`, `m, n` is the dimension of `maze`\n- Space: `O(m*n)`\n### Implementation\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n q = collections.deque([(*entrance, 0)])\n m, n = len(maze), len(maze[0])\n maze[entrance[0]][entrance[1]] == \'+\' \n while q:\n x, y, c = q.popleft()\n if (x == 0 or x == m-1 or y == 0 or y == n-1) and [x, y] != entrance:\n return c\n for i, j in [(x+_x, y+_y) for _x, _y in [(-1, 0), (1, 0), (0, -1), (0, 1)]]:\n if 0 <= i < m and 0 <= j < n and maze[i][j] == \'.\':\n maze[i][j] = \'+\'\n q.append((i, j, c + 1))\n return -1\n``` | 16 | 0 | ['Breadth-First Search', 'Queue', 'Python', 'Python3'] | 2 |
nearest-exit-from-entrance-in-maze | Simple BFS Solution | C++ without explanation | simple-bfs-solution-c-without-explanatio-s2x8 | \nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& m, vector<int>& e) \n {\n int r=size(m);\n int c=size(m[0]); \n i | shivaye | NORMAL | 2021-07-10T16:04:47.513731+00:00 | 2021-07-10T16:04:47.513758+00:00 | 1,010 | false | ```\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& m, vector<int>& e) \n {\n int r=size(m);\n int c=size(m[0]); \n int i=e[0];\n int j=e[1];\n queue<pair<int,int>> q;\n int cnt=1;\n if(i+1<r and m[i+1][j]==\'.\')\n {\n q.push({i+1,j});\n m[i+1][j]=\'+\';\n }\n if(i-1>=0 and m[i-1][j]==\'.\')\n {\n q.push({i-1,j});\n m[i-1][j]=\'+\';\n }\n if(j+1<c and m[i][j+1]==\'.\')\n {\n q.push({i,j+1});\n m[i][j+1]=\'+\';\n }\n if(j-1>=0 and m[i][j-1]==\'.\')\n {\n q.push({i,j-1});\n m[i][j-1]=\'+\';\n }\n m[i][j]=\'+\';\n while(!q.empty())\n {\n int sz=q.size();\n while(sz--)\n {\n auto front = q.front();\n q.pop();\n i=front.first;\n j=front.second;\n if(i==0 or j==0 or i==r-1 or j==c-1)\n return cnt;\n if(i+1<r and m[i+1][j]==\'.\')\n {\n q.push({i+1,j});\n m[i+1][j]=\'+\';\n }\n if(i-1>=0 and m[i-1][j]==\'.\')\n {\n q.push({i-1,j});\n m[i-1][j]=\'+\';\n }\n if(j+1<c and m[i][j+1]==\'.\')\n {\n q.push({i,j+1});\n m[i][j+1]=\'+\';\n }\n if(j-1>=0 and m[i][j-1]==\'.\')\n {\n q.push({i,j-1});\n m[i][j-1]=\'+\';\n }\n }\n cnt++;\n }\n return -1;\n \n }\n};\n``` | 12 | 0 | [] | 2 |
nearest-exit-from-entrance-in-maze | [JavaScript] Neat: bfs | javascript-neat-bfs-by-mxn42-4j2m | js\nconst nearestExit = (maze, [y0, x0]) => {\n maze[y0][x0] = \'@\'\n const queue = [[y0, x0, 0]]\n while (queue.length) {\n const [y, x, step] | mxn42 | NORMAL | 2022-11-21T02:06:26.177749+00:00 | 2024-02-24T20:17:45.264999+00:00 | 1,087 | false | ```js\nconst nearestExit = (maze, [y0, x0]) => {\n maze[y0][x0] = \'@\'\n const queue = [[y0, x0, 0]]\n while (queue.length) {\n const [y, x, step] = queue.shift()\n for (const [dy, dx] of [[-1, 0], [0, -1], [1, 0], [0, 1]]) {\n const ny = y + dy, nx = x + dx\n if (!maze[ny]?.[nx]) {\n if (step) return step\n } else if (maze[ny][nx] === \'.\') {\n queue.push([ny, nx, step + 1])\n maze[ny][nx] = \'*\'\n }\n }\n }\n return -1\n}\n```\n | 11 | 0 | ['JavaScript'] | 2 |
nearest-exit-from-entrance-in-maze | Simple BFS using Java | O(m*n) time and O(1) space. | simple-bfs-using-java-omn-time-and-o1-sp-z9bi | \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 | eshwaraprasad | NORMAL | 2024-08-27T17:50:37.272770+00:00 | 2024-08-27T17:50:37.272811+00:00 | 1,002 | false | \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``` | 10 | 0 | ['Breadth-First Search', 'Java'] | 1 |
nearest-exit-from-entrance-in-maze | ✔️ C++ solution | BFS | c-solution-bfs-by-coding_menance-j2ks | The better approach to this question is using breadth-first-search (BFS) than depth-first-search (DFS)\n\nC++ []\nclass Solution {\npublic:\n int nearestExit(v | coding_menance | NORMAL | 2022-11-21T03:19:15.790386+00:00 | 2022-11-21T03:19:15.790421+00:00 | 2,519 | false | The better approach to this question is using breadth-first-search (BFS) than depth-first-search (DFS)\n\n``` C++ []\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& grid, vector<int>& e) {\n int y= grid.size() ,yend= grid.size() - 1, x= grid[0].size() ,xend= grid[0].size() - 1, answer = 0;\n \n queue<tuple<int,int,int>> q;\n q.push({e[0], e[1], 0});\n \n while(!q.empty()){\n auto [cy,cx, w] = q.front(); q.pop();\n if(grid[cy][cx] == \'+\') continue;\n grid[cy][cx] = \'+\';\n if(cy == 0 || cy == yend || cx == 0 || cx == xend ){\n if(cy == e[0] && cx == e[1]);\n else return w;\n }\n w++;\n if(cy && grid[cy-1][cx] == \'.\') q.push({cy-1,cx,w});\n if(cy != yend && grid[cy+1][cx] == \'.\') q.push({cy+1,cx,w});\n if(cx && grid[cy][cx-1] == \'.\') q.push({cy,cx-1,w});\n if(cx != xend && grid[cy][cx+1] == \'.\') q.push({cy,cx+1,w});\n }\n \n \n return -1; \n }\n};\n```\n\n*Upvote if you liked it* | 10 | 0 | ['Breadth-First Search', 'C++'] | 0 |
nearest-exit-from-entrance-in-maze | Issues with DFS code identified!!! | C++ | Working + Not Working Solution | issues-with-dfs-code-identified-c-workin-t4on | The solution below passes all the test cases.\n\n\nclass Solution {\npublic: \n typedef long long ll;\n ll dp[105][105];\n bool seen[105][105];\n | dedoced | NORMAL | 2021-07-10T19:24:00.352318+00:00 | 2021-07-10T19:26:14.645116+00:00 | 1,004 | false | The solution below passes all the test cases.\n\n```\nclass Solution {\npublic: \n typedef long long ll;\n ll dp[105][105];\n bool seen[105][105];\n int x[4] = {1, -1, 0, 0};\n int y[4] = {0, 0, 1, -1};\n int srcx, srcy;\n ll rec(vector<vector<char>>& arr, int row, int col){\n \n if((row != srcx or col != srcy) and (row == 0 or col == 0 or row == arr.size()-1 or col == arr[0].size()-1)) return 0;\n \n if(dp[row][col] != -1) return dp[row][col];\n \n seen[row][col] = true;\n \n ll ans = INT_MAX;\n for(int i=0; i<4; i++){\n int xx = row + x[i], yy = col + y[i];\n if(xx < 0 or yy < 0 or xx >= arr.size() or yy >= arr[0].size() or arr[xx][yy] == \'+\' or seen[xx][yy]) continue;\n ans = min(ans, 1 + rec(arr, row + x[i], col + y[i]));\n }\n \n \n seen[row][col] = false;\n \n \n return dp[row][col] = ans;\n }\n \n int nearestExit(vector<vector<char>>& arr, vector<int>& src) {\n memset(dp, -1, sizeof(dp));\n memset(seen, false, sizeof(seen));\n srcx = src[0], srcy = src[1];\n ll ans = rec(arr, src[0], src[1]);\n\n if(ans >= INT_MAX) return -1;\n return ans;\n }\n};\n```\n\n**Twist**\nJust modify the below mentioned code fragment, which simply swaps the ```x[]``` and ```y[]``` array but the logic behind is intact. BANGG!!! The code no longer works !\n\n* Earlier:\n\n```\nint x[4] = {1, -1, 0, 0};\nint y[4] = {0, 0, 1, -1};\n```\n\n* Modified (Code not working):\n```\nint x[4] = {0, 0, 1, -1};\nint y[4] = {1, -1, 0, 0};\n```\n\nAlthough only 1 test case fails, with the above modification but still it gives us an intuition that DFS is not suitable for the forementioned problem, like it may work for most of the cases but it will fail in other cases, just like Greedy algorithm fails in some cases of Knapsack problem. So, the bottom line is to use BFS instead to get a correct answer always! | 9 | 0 | [] | 6 |
nearest-exit-from-entrance-in-maze | WHY TLE WITH DFS?? PLS HELP | why-tle-with-dfs-pls-help-by-shivambunge-ltbj | Im counting all the possible path lengths and returning min of them\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) | ShivamBunge | NORMAL | 2021-07-10T16:06:11.992455+00:00 | 2021-07-10T16:07:40.917313+00:00 | 889 | false | Im counting all the possible path lengths and returning min of them\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n n=len(maze)\n m=len(maze[0])\n ans=[]\n def dfs(maze,i,j,c,visited):\n \n if [i,j]!=entrance and (i==0 or i==(n-1) or j==0 or j==(m-1)):\n ans.append(c)\n return \n for x,y in [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:\n if (x,y) not in visited and x>=0 and x<=(n-1) and y>=0 and y<=(m-1):\n if maze[x][y]==\'.\' :\n visited.add((x,y))\n dfs(maze,x,y,c+1,visited)\n visited.remove((x,y))\n \n \n dfs(maze,entrance[0],entrance[1],0,set((entrance[0],entrance[1])))\n return min(ans) if ans!=[] else -1\n | 9 | 3 | [] | 3 |
nearest-exit-from-entrance-in-maze | C++ SOLUTION USING BFS | c-solution-using-bfs-by-shruti_mahajan-dovp | \nclass Solution {\npublic:\n vector<int> r={0,0,-1,1};\n vector<int> c={-1,1,0,0};\n int nearestExit(vector<vector<char>>& ma, vector<int>& e) {\n | shruti_mahajan | NORMAL | 2021-07-10T16:01:29.051058+00:00 | 2021-07-10T19:28:17.536788+00:00 | 950 | false | ```\nclass Solution {\npublic:\n vector<int> r={0,0,-1,1};\n vector<int> c={-1,1,0,0};\n int nearestExit(vector<vector<char>>& ma, vector<int>& e) {\n int n=ma.size(),m=ma[0].size(),res=0;\n int s1=e[0],s2=e[1];\n queue<pair<int,int>> q;\n ma[s1][s2]=\'+\';\n q.push({s1,s2});\n while(!q.empty())\n {\n int s=q.size();\n res++;\n for(int k=0;k<s;k++)\n {\n auto j=q.front();\n for(int p=0;p<4;p++)\n {\n int p1=j.first+r[p],p2=j.second+c[p];\n if(p1<0||p2<0||p1>=n||p2>=m||ma[p1][p2]==\'+\')\n continue;\n if(p1==0||p2==0||p1==n-1||p2==m-1)\n return(res);\n ma[p1][p2]=\'+\';\n q.push({p1,p2});\n }\n q.pop();\n }\n }\n return(-1);\n }\n};\n``` | 9 | 3 | [] | 4 |
nearest-exit-from-entrance-in-maze | ✅✅✅ 614 ms, faster than 98.64% of Python3 || Easy to Understand | 614-ms-faster-than-9864-of-python3-easy-xo7nu | \n\n# Intuition\nThe maze consists of open spaces (\'.\') and walls (\'+\'). An exit is defined as any open space located at the boundary of the maze, excluding | denyskulinych | NORMAL | 2024-05-24T21:30:47.665590+00:00 | 2024-05-24T21:30:47.665615+00:00 | 1,253 | false | \n\n# Intuition\nThe maze consists of open spaces (\'.\') and walls (\'+\'). An exit is defined as any open space located at the boundary of the maze, excluding the entrance itself. The goal is to use a **breadth-first search (BFS)** to explore the shortest path from the entrance to the nearest exit.\n\n# Approach\nTo solve this problem, we can use the **BFS** **algorithm**, which is well-suited for finding the shortest path in an unweighted grid. BFS will explore all possible moves level by level, ensuring that we find the shortest path to the nearest exit.\n1.\tInitialize a queue with the entrance position and a step counter set to 0.\n2.\tMark the entrance as visited by replacing the value at the entrance position with \'+\'.\n3.\tWhile the queue is not empty, dequeue the front element to get the current position and step count.\n4.\tFor each of the four possible directions (up, down, left, right), calculate the new position.\n5.\tIf the new position is within the maze bounds and is an open space (\'.\'), check if it is on the boundary of the maze.\n- If it is on the boundary, return the current step count plus one as the result.\n- Otherwise, mark the new position as visited and enqueue it with the incremented step count.\n6.\tIf the queue is exhausted without finding an exit, return -1.\n\n# Complexity\n- Time complexity: ***O(m x n)***\nThe time complexity of the algorithm is *O(m x n)*, where *m* is the number of rows and *n* is the number of columns in the maze. This is because, in the worst case, we may need to visit every cell in the maze.\n\n- Space complexity: ***O(max(m, n))***\n\n# Code\n```\nfrom collections import deque\n\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n m = len(maze)\n n = len(maze[0])\n\n queue = deque([(entrance[0], entrance[1], 0)]) # step 1\n maze[entrance[0]][entrance[1]] = "+" # step 2\n\n while queue:\n row, col, steps = queue.popleft() # step 3\n\n for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: # step 4\n nr, nc = row + dy, col + dx\n if 0 <= nr < m and 0 <= nc < n and maze[nr][nc] == ".": # step 5\n if (nr == 0 or nr == m - 1) or (nc == 0 or nc == n - 1):\n return steps + 1\n\n maze[nr][nc] = "+"\n queue.append((nr, nc, steps + 1))\n\n return -1 # step 6\n \n \n``` | 8 | 0 | ['Breadth-First Search', 'Queue', 'Python3'] | 2 |
nearest-exit-from-entrance-in-maze | Python3 Breadth First Search Solution | python3-breadth-first-search-solution-by-x2pm | \n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: Lis | palak29jain05 | NORMAL | 2023-12-16T19:12:17.584653+00:00 | 2023-12-16T19:12:17.584674+00:00 | 858 | false | \n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n m = len(maze)\n n = len(maze[0])\n\n queue = collections.deque()\n queue.append((entrance[0], entrance[1], 0))\n visited = set()\n visited.add((entrance[0], entrance[1]))\n\n while queue:\n for _ in range(len(queue)):\n r, c, level = queue.popleft()\n\n if [r, c] != entrance:\n if r == 0 or r == m-1 or c == 0 or c == n-1:\n return level\n\n for nr, nc in [(r, c+1), (r, c-1), (r+1, c), (r-1, c)]:\n if 0 <= nr < m and 0 <= nc < n and (nr, nc) not in visited and maze[nr][nc] == \'.\':\n queue.append((nr, nc, level + 1))\n visited.add((nr, nc))\n\n return -1\n \n``` | 7 | 0 | ['Python3'] | 2 |
nearest-exit-from-entrance-in-maze | ✅[C++] Just do BFS !!......still getting TLE? See, Why | c-just-do-bfs-still-getting-tle-see-why-gzqys | Thought Process:\nSince it is asked to get the shortest path (nearest exit), first thought that should come to us is BFS.\nTHATS IT !!\n\n\nclass Solution {\npu | devil16 | NORMAL | 2022-11-21T06:39:10.461868+00:00 | 2022-11-21T06:39:10.461915+00:00 | 1,145 | false | # Thought Process:\nSince it is asked to get the shortest path (nearest exit), first thought that should come to us is **BFS**.\nTHATS IT !!\n\n```\nclass Solution {\npublic:\n bool check_constraint (int i, int j, int m, int n){\n return (i >= 0 && i < m && j >= 0 && j < n);\n }\n \n bool check_boundary (int i, int j, int m, int n){ \n return (i == 0 || i == m-1 || j == 0 || j == n-1);\n }\n\t\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int level = 0, m = maze.size(), n = maze[0].size();\n queue<vector<int>> q;\n vector<vector<bool>> vis (m, vector<bool>(n,0));\n q.push (entrance);\n \n vis[entrance[0]][entrance[1]] = 1;\n \n while (!q.empty ()){\n int len = q.size();\n \n for (int i = 0; i < len; i++){\n auto x = q.front ()[0];\n auto y = q.front ()[1];\n q.pop ();\n \n\t\t\t\t//go down\n if (check_constraint (x+1,y,m,n) && !vis[x+1][y] && maze[x+1][y] == \'.\'){\n if (check_boundary(x+1,y,m,n)) return level+1;\n \n vis[x+1][y] = 1;\n q.push ({x+1,y});\n }\n \n\t\t\t\t// go up\n if (check_constraint (x-1,y,m,n) && !vis[x-1][y]&& maze[x-1][y] == \'.\'){\n if (check_boundary(x-1,y, m,n)) return level+1;\n \n vis[x-1][y] = 1;\n q.push ({x-1,y});\n }\n \n\t\t\t\t//go right\n if (check_constraint (x,y+1,m,n) && !vis[x][y+1] && maze[x][y+1] == \'.\'){\n if (check_boundary(x,y+1,m,n)) return level+1;\n \n vis[x][y+1] = 1;\n q.push ({x,y+1});\n }\n \n\t\t\t\t//go left\n if (check_constraint (x,y-1,m,n) && !vis[x][y-1] && maze[x][y-1] == \'.\'){\n if (check_boundary(x,y-1,m,n)) return level+1;\n \n vis[x][y-1] = 1;\n q.push ({x,y-1});\n }\n }\n \n level++;\n }\n \n return -1;\n }\n};\n```\n\n# Complexities:\n**TC:** O(number of empty cells)\n**SC:** O(n * m) | 7 | 0 | ['C'] | 2 |
nearest-exit-from-entrance-in-maze | [Go] Solution BFS || 100% memory || 90+% runtime | go-solution-bfs-100-memory-90-runtime-by-gedb | Code\n\nfunc nearestExit(maze [][]byte, entrance []int) int {\n\tq := [][2]int{{entrance[0], entrance[1]}}\n\tm, n := len(maze), len(maze[0])\n\tmaze[entrance[0 | user9647qb | NORMAL | 2022-11-21T06:07:39.464416+00:00 | 2022-11-21T06:07:39.464448+00:00 | 558 | false | # Code\n```\nfunc nearestExit(maze [][]byte, entrance []int) int {\n\tq := [][2]int{{entrance[0], entrance[1]}}\n\tm, n := len(maze), len(maze[0])\n\tmaze[entrance[0]][entrance[1]] = \'+\'\n\n\tsteps := 0\n\tfor len(q) > 0 {\n\t\tfor _, v := range q {\n\t\t\tq = q[1:]\n\t\t\tif (v[0] == m-1 || v[1] == n-1 || v[0] == 0 || v[1] == 0) && !(v[0] == entrance[0] && v[1] == entrance[1]) {\n\t\t\t\treturn steps\n\t\t\t}\n\t\t\tfor _, div := range [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {\n\t\t\t\tx, y := v[0]+div[0], v[1]+div[1]\n\t\t\t\tif x >= 0 && y >= 0 && x < m && y < n && maze[x][y] != \'+\' {\n\t\t\t\t\tq = append(q, [2]int{x, y})\n\t\t\t\t\tmaze[x][y] = \'+\'\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsteps++\n\t}\n\treturn -1\n}\n\n``` | 7 | 0 | ['Go'] | 3 |
nearest-exit-from-entrance-in-maze | ✅ Python, Easy to understand BFS, 97.74% | python-easy-to-understand-bfs-9774-by-an-0p5f | \nclass Solution:\n def nearestExit(self, maze: List[List[str]], entr: List[int]) -> int:\n rows, cols = len(maze), len(maze[0])\n deq = deque( | AntonBelski | NORMAL | 2022-07-03T21:30:23.092680+00:00 | 2022-07-18T11:53:00.942488+00:00 | 822 | false | ```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entr: List[int]) -> int:\n rows, cols = len(maze), len(maze[0])\n deq = deque()\n deq.append([entr[0], entr[1], -1])\n \n while deq:\n r, c, dist = deq.popleft()\n if not (0 <= r < rows and 0 <= c < cols):\n if dist > 0:\n return dist\n continue\n if maze[r][c] == \'+\':\n continue\n \n maze[r][c] = \'+\'\n for _r, _c in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n deq.append([r + _r, c + _c, dist + 1])\n \n return -1\n```\n\nTime Complexity - ```O(N * M)```, ```756``` ms, faster than ```97.74%```\nSpace \u0421omplexity - ```O(N * M)```, ```14.4``` MB, less than ```99.05%``` | 7 | 0 | ['Breadth-First Search', 'Python'] | 3 |
nearest-exit-from-entrance-in-maze | a few solutions | a-few-solutions-by-claytonjwong-chng | Perform BFS from start.\n\n---\n\nKotlin\n\nclass Solution {\n fun nearestExit(A: Array<CharArray>, start: IntArray): Int {\n var depth = 0\n v | claytonjwong | NORMAL | 2021-07-10T16:00:33.161359+00:00 | 2021-07-10T16:19:56.753716+00:00 | 718 | false | Perform BFS from `start`.\n\n---\n\n*Kotlin*\n```\nclass Solution {\n fun nearestExit(A: Array<CharArray>, start: IntArray): Int {\n var depth = 0\n var (M, N) = listOf(A.size, A[0].size)\n var isExit = { i: Int, j: Int -> i == 0 || i == M - 1 || j == 0 || j == N - 1 }\n var q: Queue<Pair<Int,Int>> = LinkedList<Pair<Int, Int>>(listOf(Pair(start[0], start[1])))\n var seen = mutableSetOf<String>("${start[0]},${start[1]}")\n while (0 < q.size) {\n var k = q.size\n while (0 < k--) {\n var (i, j) = q.poll()\n if (isExit(i, j) && 0 < depth)\n return depth\n for ((u, v) in listOf(Pair(i - 1, j), Pair(i, j + 1), Pair(i + 1, j), Pair(i, j - 1))) {\n if (0 <= u && u < M && 0 <= v && v < N && A[u][v] == \'.\' && !seen.contains("$u,$v")) {\n q.add(Pair(u, v)); seen.add("$u,$v")\n }\n }\n }\n ++depth\n }\n return -1\n }\n}\n```\n\n*Javascript*\n```\nlet nearestExit = (A, start, depth = 0) => {\n let [M, N] = [A.length, A[0].length];\n let isExit = (i, j) => !i || i == M - 1 || !j || j == N - 1;\n let q = [[...start]];\n let seen = new Set([`${start[0]},${start[1]}`]);\n while (q.length) {\n let k = q.length;\n while (k--) {\n let [i, j] = q.shift();\n if (isExit(i, j) && depth)\n return depth;\n for (let [u, v] of [[i - 1, j], [i, j + 1], [i + 1, j], [i, j - 1]])\n if (0 <= u && u < M && 0 <= v && v < N && A[u][v] == \'.\' && !seen.has(`${u},${v}`))\n q.push([u, v]), seen.add(`${u},${v}`);\n }\n ++depth;\n }\n return -1;\n};\n```\n\n*Python3*\n```\nclass Solution:\n def nearestExit(self, A: List[List[str]], start: List[int], depth = 0) -> int:\n M, N = len(A), len(A[0])\n isExit = lambda i, j: not i or i == M - 1 or not j or j == N - 1\n q = deque([[*start]])\n seen = set([f\'{start[0]},{start[1]}\'])\n while q:\n k = len(q)\n while k:\n i, j = q.popleft()\n if isExit(i, j) and depth:\n return depth\n for u, v in [[i - 1, j], [i, j + 1], [i + 1, j], [i, j - 1]]:\n if 0 <= u < M and 0 <= v < N and A[u][v] == \'.\' and f\'{u},{v}\' not in seen:\n q.append([ u, v ]); seen.add(f\'{u},{v}\')\n k -= 1\n depth += 1\n return -1\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using VC = vector<char>;\n using VVC = vector<VC>;\n using VI = vector<int>;\n using Pair = pair<int, int>;\n using Dirs = vector<Pair>;\n using Seen = unordered_map<int, unordered_map<int, bool>>;\n using Queue = queue<Pair>;\n int nearestExit(VVC& A, VI& start, Seen seen = {}, int depth = 0) {\n int M = A.size(),\n N = A[0].size();\n auto isExit = [&](auto i, auto j) {\n return !i || i == M - 1 || !j || j == N - 1;\n };\n auto [i, j] = tie(start[0], start[1]);\n Queue q{{{ i, j }}};\n seen[i][j] = true;\n while (q.size()) {\n int k = q.size();\n while (k--) {\n auto [i, j] = q.front(); q.pop();\n if (isExit(i, j) && depth)\n return depth;\n for (auto [u, v]: Dirs{{i - 1, j}, {i, j + 1}, {i + 1, j}, {i, j - 1}})\n if (0 <= u && u < M && 0 <= v && v < N && A[u][v] == \'.\' && !seen[u][v])\n q.push({ u, v }), seen[u][v] = true;\n }\n ++depth;\n }\n return -1;\n }\n};\n``` | 7 | 0 | [] | 2 |
nearest-exit-from-entrance-in-maze | ✅[Java] Solution using BFS✅ | java-solution-using-bfs-by-staywithsaksh-b8js | Simply apply BFS on Matrix code as gived below:\n\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int r = maze.length, c | staywithsaksham | NORMAL | 2022-11-21T07:40:59.103524+00:00 | 2022-11-21T07:40:59.103561+00:00 | 737 | false | Simply apply BFS on Matrix code as gived below:\n```\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int r = maze.length, c = maze[0].length;\n int[][] directions = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n \n int sr = entrance[0], sc = entrance[1];\n maze[sr][sc] = \'+\';\n \n // Start BFS from the entrance, and use a queue `queue` to store all \n // the cells to be visited.\n Queue<int[]> queue = new LinkedList<>();\n queue.offer(new int[]{sr, sc, 0});\n \n while (!queue.isEmpty()) {\n int[] currState = queue.poll();\n int currRow = currState[0], currCol = currState[1], currDistance = currState[2];\n\n for (int[] dir : directions) {\n int nextRow = currRow + dir[0], nextCol = currCol + dir[1];\n\n // If there exists an unvisited empty neighbor:\n if (0 <= nextRow && nextRow < r && 0 <= nextCol && nextCol < c\n && maze[nextRow][nextCol] == \'.\') {\n \n // If this empty cell is an exit, return distance + 1.\n if (nextRow == 0 || nextRow == r - 1 || nextCol == 0 || nextCol == c - 1)\n return currDistance + 1;\n \n // Otherwise, add this cell to \'queue\' and mark it as visited.\n maze[nextRow][nextCol] = \'+\';\n queue.offer(new int[]{nextRow, nextCol, currDistance + 1});\n } \n }\n }\n\n return -1;\n }\n}\n```\nUpvote if you like :D | 6 | 0 | ['Breadth-First Search', 'Graph', 'Queue', 'Java'] | 1 |
nearest-exit-from-entrance-in-maze | Detailed C++ Standard Approaches BFS Approach | detailed-c-standard-approaches-bfs-appro-y1ca | This question can easily solved using a standard BFS algorithm.\n\nWe must do BFS step by step starting from the entrance and iterating level by level, so one o | sahooc029 | NORMAL | 2022-11-21T05:06:39.625453+00:00 | 2022-11-21T06:01:20.072487+00:00 | 1,406 | false | This question can easily solved using a standard **BFS** algorithm.\n\nWe must do **BFS** step by step starting from the entrance and iterating level by level, so one of the paths that we choose will be the minimum path (if it exists).\n\n**Idea :** using **BFS** to find shortest path. \n\n\n**Complexity**\nSpace Complexity: **```O(m*n)```**\nTime Complexity: **```O(m*n)```**\n(Queue will store at max **(m * n)** nodes for the same reason and push or pop requires **O(1)** time.)\n\n**C++ code (BFS) :**\n```\n\nclass Solution {\nprivate:\n vector<int> dx = {0, -1, 1, 0}, dy = {1, 0, 0, -1}; // 4 direction to move\n int m, n; // to store row and column\n\nprivate:\n // check for valid index\n bool isValid(int x, int y) {\n return x >= 0 and y >= 0 and x < m and y < n;\n }\n\n int find(vector<vector<char>> &maze, int st1, int st2) {\n // get the row and col\n m = maze.size(), n = maze[0].size();\n int mn = INT_MAX;\n\n // init the vis array and queue\n vector<vector<int>> vis(m, vector<int>(n, 0));\n queue<pair<int, int>>q;\n\n // mark the curent user cell to visited and push position in queue\n vis[st1][st2] = 1;\n q.push({st1, st2});\n\n int move = 0;\n\n // until queue is empty do move in 4 direction untill you reach exit\n while (!q.empty()) {\n // get the queue size\n int s = q.size();\n \n while (s--) {\n // take the first element from queue\n auto cur = q.front();\n q.pop(); // remove it\n\n // check if person reach to any of the boundary and also check if person making move to reach boundary i.e person doesn\'t staying at boundary initially\n if ((cur.first != st1 or cur.second != st2) and (cur.first == 0 or cur.first == m - 1 or cur.second == 0 or cur.second == n - 1)) {\n return move;\n }\n \n // check in 4 dir\n for (int i = 0; i < 4; ++i) {\n // get the new adj row and col\n int x = cur.first + dx[i];\n int y = cur.second + dy[i];\n // if the new position is not visited or it should be a valid position also it\'s not a wall then make moves\n if (isValid(x, y) and !vis[x][y] and maze[x][y] == \'.\') {\n vis[x][y] = 1;\n q.push({x, y});\n }\n }\n }\n // increment the moves\n move++;\n }\n \n // if not able to reach boundary\n return -1;\n }\n \npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n // pass the maze and starting position\n return find(maze, entrance[0], entrance[1]);\n }\n};\n\n```\n\nPLease upvote if you find this helpful. **: )**\nFeel free to comment in case of any doubt. | 6 | 0 | ['Breadth-First Search', 'Graph', 'C'] | 2 |
nearest-exit-from-entrance-in-maze | Rust using queue and set | rust-using-queue-and-set-by-yosuke-furuk-ot1w | Code\n\nuse std::collections::VecDeque;\nuse std::collections::HashSet;\n\nimpl Solution {\n pub fn nearest_exit(maze: Vec<Vec<char>>, entrance: Vec<i32>) -> | yosuke-furukawa | NORMAL | 2022-11-21T01:40:36.445289+00:00 | 2022-11-21T01:40:36.445331+00:00 | 618 | false | # Code\n```\nuse std::collections::VecDeque;\nuse std::collections::HashSet;\n\nimpl Solution {\n pub fn nearest_exit(maze: Vec<Vec<char>>, entrance: Vec<i32>) -> i32 {\n let mut queue = VecDeque::new();\n let mut visited = HashSet::new();\n queue.push_back((entrance[0] as usize, entrance[1] as usize, 0));\n while !queue.is_empty() {\n while let Some((i, j, c)) = queue.pop_front() {\n if !visited.insert((i, j)) {\n continue;\n }\n if i == 0 || i == maze.len() - 1 || j == 0 || j == maze[0].len() - 1 {\n if i != entrance[0] as usize || j != entrance[1] as usize {\n return c;\n }\n }\n if maze[i][j] == \'.\' {\n if i > 0 && maze[i - 1][j] == \'.\' {\n queue.push_back((i - 1, j, c + 1));\n }\n if i < maze.len() - 1 && maze[i + 1][j] == \'.\' {\n queue.push_back((i + 1, j, c + 1));\n }\n if j > 0 && maze[i][j - 1] == \'.\' {\n queue.push_back((i, j - 1, c + 1));\n }\n if j < maze[0].len() - 1 && maze[i][j + 1] == \'.\' {\n queue.push_back((i, j + 1, c + 1));\n }\n }\n }\n }\n -1\n }\n}\n``` | 6 | 1 | ['Rust'] | 1 |
nearest-exit-from-entrance-in-maze | BFS Clean c# solution | bfs-clean-c-solution-by-rchshld-ivge | \n public int NearestExit(char[][] maze, int[] entrance) {\n var dirs = new [] {0, 1, 0, -1, 0};\n var q = new Queue<(int, int, int)>();\n | rchshld | NORMAL | 2022-05-01T15:50:40.222293+00:00 | 2022-05-01T15:50:40.222337+00:00 | 283 | false | ```\n public int NearestExit(char[][] maze, int[] entrance) {\n var dirs = new [] {0, 1, 0, -1, 0};\n var q = new Queue<(int, int, int)>();\n q.Enqueue((entrance[0], entrance[1], 0));\n \n while(q.Any())\n {\n var (i, j, dist) = q.Dequeue();\n if(i < 0 || i == maze.Length) continue;\n if(j < 0 || j == maze[i].Length) continue;\n if(maze[i][j] != \'.\') continue;\n maze[i][j] = \'_\';\n if(dist > 0 && (i == 0 || i == maze.Length - 1)) return dist;\n if(dist > 0 && (j == 0 || j == maze[i].Length - 1)) return dist;\n \n for(var k = 0; k < dirs.Length - 1; k++)\n q.Enqueue((i + dirs[k], j + dirs[k + 1], dist + 1));\n }\n \n return -1;\n }\n```\nTime complexety O(n*m).\nSpace complexy O(1) if we can modify the maze array and (n*m) if not. | 6 | 0 | ['Breadth-First Search', 'C#'] | 0 |
nearest-exit-from-entrance-in-maze | Python BFS | python-bfs-by-kyathamomkar-mox8 | \nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n ex,ey = entrance\n rows = len(maze)\n co | kyathamomkar | NORMAL | 2021-07-16T07:18:18.560173+00:00 | 2021-07-16T07:18:18.560226+00:00 | 260 | false | ```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n ex,ey = entrance\n rows = len(maze)\n cols = len(maze[0])\n \n def onBorder(r,c): #check if cell is on the border and not the entrance cell\n if (r in [0,rows-1] or c in [0,cols-1]) and (r,c)!=(ex,ey):\n return True\n return False\n \n def isnotwall(r,c): # check if cell is a wall\n if 0<=r<rows and 0<=c<cols and maze[r][c]==\'.\':\n return True\n return False\n \n maze[ex][ey] = \'+\'\n queue = [(ex,ey,0)]\n while queue:\n r,c,steps = queue.pop(0)\n if onBorder(r,c):\n return steps\n for r1,c1 in [(0,1),(0,-1),(1,0),(-1,0)]:\n if isnotwall(r1+r, c1+c):\n maze[r1+r][c1+c] = \'+\' # marking a cell as wall bc we dont want to visit again\n queue.append((r1+r, c1+c,steps+1))\n \n return -1\n``` | 6 | 0 | [] | 0 |
nearest-exit-from-entrance-in-maze | C++ | Straightforward BFS | Faster than 91% | c-straightforward-bfs-faster-than-91-by-9o02o | \nclass Solution {\npublic:\n int m,n;\n int dx[4] = {0,0,1,-1};\n int dy[4] = {1,-1,0,0};\n bool isBorder(int i,int j){\n return (i==0 || i= | aparna_g | NORMAL | 2021-07-14T19:49:16.615450+00:00 | 2021-07-14T19:49:34.543791+00:00 | 1,317 | false | ```\nclass Solution {\npublic:\n int m,n;\n int dx[4] = {0,0,1,-1};\n int dy[4] = {1,-1,0,0};\n bool isBorder(int i,int j){\n return (i==0 || i==m-1 || j == 0 || j == n-1);\n }\n \n bool valid(int r,int c){\n return (r>=0 && c>=0 && r<m && c<n);\n }\n \n int nearestExit(vector<vector<char>>& maze, vector<int>& ent) {\n m = maze.size() , n=maze[0].size();\n if(isBorder(ent[0] , ent[1])) \n maze[ent[0]][ent[1]] = \'+\';\n int ans = 0;\n queue<pair<int,int>> q;\n q.push({ent[0],ent[1]});\n while(!q.empty()){\n int size = q.size();\n for(int i=0;i<size;i++){\n auto top = q.front();\n q.pop();\n int x = top.first , y = top.second;\n if(maze[x][y] != \'+\' && isBorder(x,y))\n return ans;\n for(int j=0;j<4;j++){\n int r = x + dx[j];\n int c = y + dy[j];\n if(valid(r,c) && maze[r][c]==\'.\'){\n q.push({r,c});\n maze[r][c] = \'*\';\n }\n }\n }\n ans++;\n }\n return -1;\n }\n};\n``` | 6 | 0 | ['Breadth-First Search', 'C', 'C++'] | 1 |
nearest-exit-from-entrance-in-maze | java accepted BFS solution | java-accepted-bfs-solution-by-anmol676-eqq6 | This Problem is similiar to walls and land question on leetcode. Just apply the BFS . we are given a starting point . So apply BFS from that only on empty cell | anmol676 | NORMAL | 2021-07-10T16:15:43.381614+00:00 | 2021-07-10T16:20:27.261162+00:00 | 630 | false | This Problem is similiar to **walls and land** question on leetcode. Just apply the BFS . we are given a starting point . So apply BFS from that only on empty cells and whenever we are at 1st row, or 1st column or last row or last column simply return that level. \n\'\'\'\nclass Solution {\n public int nearestExit(char[][] grid, int[] entrance) {\n if (grid.length == 0 || grid[0].length == 0)\n return-1;\n \n\n int n = grid.length, m = grid[0].length;\n LinkedList<Integer> que = new LinkedList<>();\n int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n int startrow =entrance[0];\n int startcol = entrance[1];\n que.addLast(startrow * m + startcol);\n grid[startrow][startcol] = \'+\';\n int level=0;\n while (que.size() != 0) {\n int size = que.size();\n level++;\n while (size-- > 0) {\n \n int idx = que.removeFirst();\n int sr = idx / m, sc = idx % m;\n\n for (int d = 0; d < dir.length; d++) {\n int r = sr + dir[d][0];\n int c = sc + dir[d][1];\n\n if (r >= 0 && c >= 0 && r < n && c < m && grid[r][c] == \'.\') {\n if(r==0 || r== n-1 || c==0 ||c==m-1) return level;\n grid[r][c]=\'+\';\n que.addLast(r * m + c);\n }\n }\n }\n \n \n }\n return -1;\n }\n}\n\'\'\' | 6 | 1 | ['Breadth-First Search', 'Java'] | 3 |
nearest-exit-from-entrance-in-maze | Solution By Dare2Solve | Detailed Explanation | Clean Code | solution-by-dare2solve-detailed-explanat-1yg1 | Explanation []\nauthorslog.com/blog/xkpfvNACri\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entr | Dare2Solve | NORMAL | 2024-08-22T08:57:46.472594+00:00 | 2024-08-22T08:57:46.472628+00:00 | 1,188 | false | ```Explanation []\nauthorslog.com/blog/xkpfvNACri\n```\n# Code\n\n```cpp []\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n vector<tuple<int, int, int>> st;\n int rows = maze.size();\n int cols = maze[0].size();\n\n for (int i = 0; i < rows; ++i) {\n for (int j = 0; j < cols; ++j) {\n if (maze[i][j] == \'.\' && (i == 0 || i == rows - 1 || j == 0 || j == cols - 1) && !isEquals(vector<int>{i, j}, entrance)) {\n st.push_back({i, j, 0});\n }\n }\n }\n return bfs(st, maze, entrance);\n }\n\nprivate:\n bool isEquals(const vector<int>& a, const vector<int>& b) {\n return a[0] == b[0] && a[1] == b[1];\n }\n\n int bfs(vector<tuple<int, int, int>>& st, vector<vector<char>>& maze, vector<int>& start) {\n vector<vector<int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n unordered_map<int, unordered_map<int, bool>> visited;\n\n while (!st.empty()) {\n auto [row, col, len] = st.front();\n st.erase(st.begin());\n visited[row][col] = true;\n\n for (auto& dir : directions) {\n int r = row + dir[0];\n int c = col + dir[1];\n\n if (isEquals(vector<int>{r, c}, start)) return len + 1;\n if (r < 0 || c < 0 || r >= maze.size() || c >= maze[0].size() || maze[r][c] == \'+\' || visited[r][c]) continue;\n\n st.push_back({r, c, len + 1});\n visited[r][c] = true;\n }\n }\n return -1;\n }\n};\n```\n\n```python []\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n st = []\n rows, cols = len(maze), len(maze[0])\n\n for i in range(rows):\n for j in range(cols):\n if maze[i][j] == "." and (i == 0 or i == rows - 1 or j == 0 or j == cols - 1) and [i, j] != entrance:\n st.append((i, j, 0))\n\n return self.bfs(st, maze, entrance)\n\n def isEquals(self, a: List[int], b: List[int]) -> bool:\n return a[0] == b[0] and a[1] == b[1]\n\n def bfs(self, st: List[tuple], maze: List[List[str]], start: List[int]) -> int:\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n visited = set()\n\n while st:\n row, col, length = st.pop(0)\n visited.add((row, col))\n\n for r_offset, c_offset in directions:\n r, c = row + r_offset, col + c_offset\n\n if [r, c] == start:\n return length + 1\n if r < 0 or c < 0 or r >= len(maze) or c >= len(maze[0]) or maze[r][c] == "+" or (r, c) in visited:\n continue\n\n st.append((r, c, length + 1))\n visited.add((r, c))\n\n return -1\n```\n\n```java []\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n List<int[]> st = new ArrayList<>();\n int rows = maze.length;\n int cols = maze[0].length;\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (maze[i][j] == \'.\' && (i == 0 || i == rows - 1 || j == 0 || j == cols - 1) && !isEquals(new int[]{i, j}, entrance)) {\n st.add(new int[]{i, j, 0});\n }\n }\n }\n return bfs(st, maze, entrance);\n }\n\n private boolean isEquals(int[] a, int[] b) {\n return a[0] == b[0] && a[1] == b[1];\n }\n\n private int bfs(List<int[]> st, char[][] maze, int[] start) {\n int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n Set<String> visited = new HashSet<>();\n\n while (!st.isEmpty()) {\n int[] cur = st.remove(0);\n int row = cur[0], col = cur[1], len = cur[2];\n visited.add(row + "," + col);\n\n for (int[] dir : directions) {\n int r = row + dir[0];\n int c = col + dir[1];\n\n if (isEquals(new int[]{r, c}, start)) return len + 1;\n if (r < 0 || c < 0 || r >= maze.length || c >= maze[0].length || maze[r][c] == \'+\' || visited.contains(r + "," + c)) continue;\n\n st.add(new int[]{r, c, len + 1});\n visited.add(r + "," + c);\n }\n }\n return -1;\n }\n}\n```\n\n```javascript []\nvar nearestExit = function (maze, entrance) {\n let st = []\n for (let i = 0; i < maze.length; i++) {\n for (let j = 0; j < maze[0].length; j++) {\n if (maze[i][j] == "." && (i == 0 || i == maze.length - 1 || j == 0 || j == maze[0].length - 1) && !isEquals([i, j], entrance)) {\n st.push([i, j, 0])\n }\n }\n }\n return bfs(st, maze, entrance)\n};\nfunction isEquals(a, b) {\n return a[0] == b[0] && a[1] == b[1]\n}\nfunction bfs(st, maze, start) {\n let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]], visited = {}\n while (st.length) {\n const [row, col, len] = st.shift()\n visited[[row, col]] = 1\n for (let i of directions) {\n let r = row + i[0], c = col + i[1]\n if (isEquals([r, c], start)) return len + 1\n if (r < 0 || c < 0 || r > maze.length - 1 || c > maze[0].length - 1 || maze[r][c] == "+" || visited[[r, c]]) continue\n st.push([r, c, len + 1])\n visited[[r, c]] = 1\n }\n }\n return -1\n}\n``` | 5 | 0 | ['Matrix', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
nearest-exit-from-entrance-in-maze | Fully Step by step explanation. BFS Solution | fully-step-by-step-explanation-bfs-solut-bwn6 | Intuition\nThe problem involves finding the nearest exit from a given entrance in a maze. We can use Breadth-First Search (BFS) to explore possible paths from t | OtabekJurabekov | NORMAL | 2024-01-11T06:16:18.040348+00:00 | 2024-01-11T06:16:18.040378+00:00 | 209 | false | # Intuition\nThe problem involves finding the nearest exit from a given entrance in a maze. We can use Breadth-First Search (BFS) to explore possible paths from the entrance and stop when we reach an exit.\n\n# Approach\n1. **Initialize**: Start by initializing the maze, the entrance coordinates, and the directions to move (up, down, left, right).\n2. **BFS**: Use BFS to explore the maze, marking the distance from the entrance to each cell. Stop the BFS when an exit is found.\n3. **Check for Exit on the Border**: While exploring, check if the current cell is on the border. If it is, return the distance as soon as an exit is found. This optimization reduces unnecessary exploration.\n4. **Return Result**: If no exit is found, return -1.\n\n# Step-by-Step Explanation\n1. **Initialization:** The code starts by including necessary headers, defining the Solution class, and initializing variables including the maze, entrance coordinates, and movement directions.\n2. **BFS:** The Breadth-First Search (BFS) algorithm is employed to explore the maze. A distance array is used to store the shortest distance from the entrance to each cell.\n3. **Check for Exit on the Border:** While exploring, the code checks if the current cell is on the border. If so, it returns the distance as soon as an exit is found. This is an optimization to reduce unnecessary exploration.\n4. **Return Result:** If no exit is found during the BFS, the function returns -1.\n\n\n# Complexity\n- **Time complexity:** The time complexity is O(m * n) where m is the number of rows and n is the number of columns in the maze. In the worst case, we may need to visit every cell in the maze.\n- **Space complexity:** The space complexity is also O(m * n) for the distance array used to store the shortest distance from the entrance to each cell.\n\n\n\n# Code\n```cpp\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int m = maze.size();\n int n = maze[0].size();\n\n vector<vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n \n // Initialize distance array with maximum values\n vector<vector<int>> distance(m, vector<int>(n, INT_MAX));\n distance[entrance[0]][entrance[1]] = 0;\n\n // Queue for BFS\n queue<pair<int, int>> q;\n q.push({entrance[0], entrance[1]});\n\n // BFS\n while (!q.empty()) {\n int x = q.front().first;\n int y = q.front().second;\n q.pop();\n\n for (auto& dir : directions) {\n int newX = x + dir[0];\n int newY = y + dir[1];\n\n // Check if the new position is valid\n if (newX >= 0 && newX < m && newY >= 0 && newY < n && maze[newX][newY] == \'.\' && distance[newX][newY] == INT_MAX) {\n // Update the distance and add the new position to the queue\n distance[newX][newY] = distance[x][y] + 1;\n q.push({newX, newY});\n\n // Check if we reached an exit on the border\n if (newX == 0 || newX == m - 1 || newY == 0 || newY == n - 1) {\n return distance[newX][newY];\n }\n }\n }\n }\n\n // If no exit is found\n return -1;\n }\n};\n\n | 5 | 0 | ['C++'] | 0 |
nearest-exit-from-entrance-in-maze | BFS Solution | C++ | bfs-solution-c-by-manannjain-nr1d | Intuition\nStarting in every direction from the entrance we move by 1 step and as soon we approach a boundary return the steps.\n\n# Approach\nApply BFS which w | manannjain | NORMAL | 2022-11-21T19:45:05.913298+00:00 | 2022-11-21T19:45:05.913328+00:00 | 596 | false | # Intuition\nStarting in every direction from the entrance we move by 1 step and as soon we approach a boundary return the steps.\n\n# Approach\nApply BFS which works radially outwards from the entrance point.\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n queue<vector<int>> q;\n int ans = 0;\n int n = maze.size();\n int m = maze[0].size();\n q.push({entrance[0],entrance[1],0});\n maze[entrance[0]][entrance[1]] = \'#\';\n while(!q.empty())\n {\n int i = q.front()[0];\n int j = q.front()[1];\n int d = q.front()[2];\n q.pop();\n if(i==0||i==n-1 || j==0 || j == m-1)\n {\n if(i!=entrance[0] || j!=entrance[1])\n return d;\n }\n if(i+1<n and i>=0 and j<m and j>=0 and maze[i+1][j]==\'.\')\n {\n q.push({i+1,j,d+1});\n maze[i+1][j] = \'#\';\n } \n if(i<n and i-1>=0 and j<m and j>=0 and maze[i-1][j]==\'.\')\n {\n q.push({i-1,j,d+1});\n maze[i-1][j] = \'#\';\n } \n if(i<n and i>=0 and j+1<m and j>=0 and maze[i][j+1]==\'.\')\n {\n q.push({i,j+1,d+1});\n maze[i][j+1] = \'#\';\n } \n if(i<n and i>=0 and j<m and j-1>=0 and maze[i][j-1]==\'.\')\n {\n q.push({i,j-1,d+1});\n maze[i][j-1] = \'#\';\n } \n }\n return -1;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
nearest-exit-from-entrance-in-maze | JAVA || Why BFS || Simple Steps | java-why-bfs-simple-steps-by-jain2013103-h1x0 | 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 | jain20131035 | NORMAL | 2022-11-21T04:47:16.563719+00:00 | 2022-11-21T04:47:16.563762+00:00 | 987 | false | 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``` | 5 | 0 | ['Breadth-First Search', 'Java'] | 0 |
nearest-exit-from-entrance-in-maze | Fastest, Python BFS solution | fastest-python-bfs-solution-by-beneath_o-zo5o | \nclass Solution:\n def nearestExit(self, grid: List[List[str]], entrance: List[int]) -> int:\n m=len(grid)\n n=len(grid[0])\n lst=[[ent | beneath_ocean | NORMAL | 2022-10-17T11:25:22.849703+00:00 | 2022-10-17T11:25:22.849735+00:00 | 1,413 | false | ```\nclass Solution:\n def nearestExit(self, grid: List[List[str]], entrance: List[int]) -> int:\n m=len(grid)\n n=len(grid[0])\n lst=[[entrance[0],entrance[1],0]]\n visited=[[-1]*n for i in range(m)]\n row=[-1,1,0,0]\n col=[0,0,-1,1]\n visited[entrance[0]][entrance[1]]=1\n while lst:\n x,y,d=lst.pop(0)\n for i in range(4):\n if x+row[i]>=0 and x+row[i]<m and y+col[i]>=0 and y+col[i]<n and visited[x+row[i]][y+col[i]]==-1 and grid[x+row[i]][y+col[i]]==\'.\':\n if x+row[i]==0 or x+row[i]==m-1 or y+col[i]==0 or y+col[i]==n-1:\n return d+1\n lst.append([x+row[i],y+col[i],d+1])\n visited[x+row[i]][y+col[i]]=1\n return -1\n``` | 5 | 0 | ['Breadth-First Search', 'Graph', 'Python', 'Python3'] | 1 |
nearest-exit-from-entrance-in-maze | Simple BFS (C++) code | simple-bfs-c-code-by-rajat241302-bp0w | \nclass Solution\n{\n\tqueue<pair<int, int>> q1;\n\tvector<vector<int>> visited;\n\tint bfs(vector<vector<char>> &grid, int i, int j, vector<vector<int>> visi)\ | rajat241302 | NORMAL | 2022-06-04T17:10:43.580497+00:00 | 2022-06-04T17:10:43.580544+00:00 | 829 | false | ```\nclass Solution\n{\n\tqueue<pair<int, int>> q1;\n\tvector<vector<int>> visited;\n\tint bfs(vector<vector<char>> &grid, int i, int j, vector<vector<int>> visi)\n\t{\n\t\tint xn[] = {1, -1, 0, 0};\n\t\tint yn[] = {0, 0, -1, 1};\n\t\tqueue<pair<int, int>> q;\n\t\tvisited[i][j] = 1;\n\t\tq.push({i, j});\n\t\tq1.push({i, j});\n\t\tint ans = INT_MAX;\n\t\twhile (!q.empty())\n\t\t{\n\t\t\tint x = q.front().first;\n\t\t\tint y = q.front().second;\n\t\t\tq.pop();\n\n\t\t\tfor (int i1 = 0; i1 < 4; i1++)\n\t\t\t{\n\t\t\t\ti = x + xn[i1];\n\t\t\t\tj = y + yn[i1];\n\t\t\t\tif (i >= grid.size() || j >= grid[0].size() || grid[i][j] == \'+\' || visited[i][j] == 1)\n\t\t\t\t\tcontinue;\n\t\t\t\tvisi[i][j] = visi[x][y] + 1;\n\t\t\t\tvisited[i][j] = 1;\n\t\t\t\tq.push({i, j});\n\t\t\t\tq1.push({i, j});\n\t\t\t\tif (i == 0 || i == grid.size() - 1 || j == 0 || j == grid[0].size() - 1)\n\t\t\t\t\tans = min(visi[i][j], ans);\n\t\t\t\t\t\t}\n\t\t}\n\t\tif (ans == INT_MAX)\n\t\t\treturn -1;\n\t\telse\n\t\t\treturn ans - 1;\n\t}\n\npublic:\n\tint nearestExit(vector<vector<char>> &maze, vector<int> &e)\n\t{\n\t\tint i = e[0];\n\t\tint j = e[1];\n\n\t\tvector<vector<int>> visi;\n\n\t\tint xn[] = {1, -1, 0, 0};\n\t\tint yn[] = {0, 0, -1, 1};\n\n\t\tint n = maze.size();\n\t\tint m = maze[0].size();\n\t\tvisited.resize(n + 1, vector<int>(m + 1, 0));\n\n\t\tvisi.resize(n + 1, vector<int>(m + 1, 0));\n\t\tvisi[i][j] = 1;\n\t\treturn bfs(maze, i, j, visi);\n\t}\n};\n``` | 5 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Graph', 'Queue', 'C', 'C++'] | 0 |
nearest-exit-from-entrance-in-maze | C++ Solution using BFS (with comments) | c-solution-using-bfs-with-comments-by-ar-vkhh | The main idea is to perform BFS in all 4 directions and return the number of steps as soon as you find a valid empty cell.\n\n\nclass Solution {\npublic:\n / | archit-dev | NORMAL | 2022-05-26T16:18:11.365198+00:00 | 2022-05-26T16:18:11.365243+00:00 | 281 | false | The main idea is to perform BFS in all 4 directions and return the number of steps as soon as you find a valid empty cell.\n\n```\nclass Solution {\npublic:\n //checks if the coordinates of the cell are that of an unvisited valid empty cell\n bool isValid(int x,int y,int n,int m, vector<vector<char>>& maze,vector<vector<int>>& visited){\n if(x>=0 && x<n && y>=0 && y< m && maze[x][y]!=\'+\' && visited[x][y]!=1){\n return true;\n }\n return false;\n }\n \n //checks if the cell is a valid exit point\n bool isExit(int x,int y,int startX,int startY, vector<vector<char>>& maze,vector<vector<int>>& visited){\n if(x==startX && y==startY) return false;\n if( (x==0 || x==maze.size()-1 || y==0 || y==maze[0].size()-1) \n && maze[x][y]!=\'+\')\n {\n return true;\n }\n return false;\n }\n \n //main BFS function \n int bfsHelper(vector<vector<char>>& maze,vector<vector<int>>& visited,int startX,int startY){\n queue<vector<int>>Queue;\n Queue.push({startX,startY,0});\n while(!Queue.empty()){\n int x = Queue.front()[0];\n int y = Queue.front()[1];\n int steps = Queue.front()[2];\n Queue.pop();\n //if you reach a valid exit, return the number of steps\n if(isExit(x,y,startX,startY,maze,visited)) return steps;\n int dx[4] = {0,-1,0,1};\n int dy[4] = {-1,0,1,0};\n //check in the 4 directions that you can travel\n for(int i=0;i<4;i++){\n int newX = x+dx[i] , newY = y+dy[i];\n //if the coordinates of the cell are that of \n //an unvisited valid empty cell, add it to the queue \n //and mark it as visited.\n if(isValid(newX,newY,maze.size(),maze[0].size(),maze,visited)){\n Queue.push({newX,newY,steps+1});\n visited[newX][newY] = 1;\n }\n }\n }\n //if you could not find a valid exit point, return -1\n return -1;\n }\n \n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int n = maze.size();\n int m = maze[0].size();\n //create a 2d matrix and mark all the cells as -1, \n //denoting that they have not been visited yet.\n vector<vector<int>>visited(n,vector<int>(m,-1));\n return bfsHelper(maze,visited,entrance[0],entrance[1]);\n }\n};\n``` | 5 | 0 | ['Breadth-First Search', 'Graph', 'C'] | 0 |
nearest-exit-from-entrance-in-maze | [Python 3] BFS - Clean, simple easy to understand | python-3-bfs-clean-simple-easy-to-unders-s9fc | \ndef nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n\tm, n = len(maze), len(maze[0])\n\tq = deque([(entrance[0], entrance[1])])\n\tstep | dolong2110 | NORMAL | 2022-04-27T11:24:25.603994+00:00 | 2022-04-27T11:24:25.604022+00:00 | 364 | false | ```\ndef nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n\tm, n = len(maze), len(maze[0])\n\tq = deque([(entrance[0], entrance[1])])\n\tsteps = 0\n\twhile q:\n\t\tl = len(q)\n\t\tfor _ in range(l):\n\t\t\tr, c = q.popleft()\n\t\t\tif r < 0 or r == m or c < 0 or c == n or maze[r][c] == \'+\':\n\t\t\t\tcontinue\n\t\t\tif (r == m - 1 or c == n - 1 or r == 0 or c == 0) and steps:\n\t\t\t\treturn steps\n\t\t\tmaze[r][c] = \'+\'\n\t\t\tq.extend([(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)])\n\t\tsteps += 1\n\treturn -1\n``` | 5 | 0 | ['Breadth-First Search', 'Python', 'Python3'] | 0 |
nearest-exit-from-entrance-in-maze | Python and C++ Solution with Explanation - BFS | python-and-c-solution-with-explanation-b-jxvs | It is a commonly known concept that we can use either DFS or BFS to find if there is a path from one node to another in a graph. You check out Abdul Bari\u2019s | vishnusreddy | NORMAL | 2021-07-11T11:26:08.661622+00:00 | 2021-07-11T11:26:08.661654+00:00 | 2,093 | false | It is a commonly known concept that we can use either DFS or BFS to find if there is a path from one node to another in a graph. You check out Abdul Bari\u2019s video on YouTube if you want a clear about both of these traversals.\n\nThe basic idea here is to perform a breadth-first search on the given input matrix looking for the first exit point. We can use DFS as well, but the issue is that we would have to check for every path, unlike BFS. In BFS, as soon as we get an exit, we can be assured that it is the shortest path because BFS is a level order traversal. \n\nFor a detailed solution, check out my blog on hello ML at https://helloml.org/nearest-exit-from-entrance-in-maze-solution-to-leetcode-problem/. \n\n## Solution in Python\n```python\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n # Creating a queue for BFS\n queue = []\n queue.append(entrance)\n \n moves = 1\n rows = len(maze)\n columns = len(maze[0])\n # All Available movements\n directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n # Setting the entrace as visited\n maze[entrance[0]][entrance[1]] = \'+\'\n # As long as queue is not empty\n while(queue):\n l = len(queue)\n # Now exploring every element in the queue\n for k in range(0, l):\n [i, j] = queue.pop(0)\n # Trying all possible directions\n for t in range(0, 4):\n x = i + directions[t][0]\n y = j + directions[t][1]\n # Invalid position\n if(x < 0 or y < 0 or x >= rows or y >= columns or maze[x][y] == \'+\'):\n continue\n # Exit Reached\n elif(x == 0 or y == 0 or x == rows -1 or y == columns -1 ):\n return moves\n # Mark as Visited\n maze[x][y] = \'+\'\n queue.append([x, y])\n moves += 1\n return -1\n```\n## Solution in C++\n```cpp\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& e) {\n queue<pair<int,int>> q;\n q.push({e[0],e[1]});\n\n int moves=1;\n int rows=maze.size();\n int cols=maze[0].size();\n\n vector<vector<int>> offsets={{0,1},{1,0},{0,-1},{-1,0}};\n\n maze[e[0]][e[1]]=\'+\';\n while(!q.empty())\n {\n int l=q.size();\n //for every node in the queue visit all of it\'s adjacent nodes which are not visited yet\n for(int k=0;k<l;k++)\n {\n auto [i,j]=q.front();\n q.pop();\n \n //try all 4 directions from the current cell\n for(int l=0;l<4;l++)\n {\n int x=i+offsets[l][0];\n int y=j+offsets[l][1];\n //a invalid move\n if(x<0 || y<0 || x>=rows || y>=cols || maze[x][y]==\'+\')\n continue;\n //if we have reached the exit then current moves are the min moves to reach the exit\n if(x==0 || y==0 || x==rows-1 || y==cols-1)\n return moves;\n //block the cell as we have visited\n maze[x][y]=\'+\';\n q.push({x,y});\n }\n }\n //increment the moves\n moves++;\n }\n return -1;\n }\n};\n``` | 5 | 0 | ['Breadth-First Search', 'C', 'Python', 'C++'] | 4 |
nearest-exit-from-entrance-in-maze | C++ | BFS | Easy and intuitive | c-bfs-easy-and-intuitive-by-technisrahul-3pig | \nclass Solution {\npublic:\n bool isSafe(int i,int j ,int r,int c){\n if(i<0 || i >=r || j <0 || j >=c) return false;\n return true;\n }\n | technisRahulk | NORMAL | 2021-07-10T19:12:59.211158+00:00 | 2021-07-10T19:12:59.211191+00:00 | 249 | false | ``` \nclass Solution {\npublic:\n bool isSafe(int i,int j ,int r,int c){\n if(i<0 || i >=r || j <0 || j >=c) return false;\n return true;\n }\n bool isExit(int i,int j,int r ,int c){\n if(i!=0 and j!=0 and i!=r-1 and j!=c-1) return false;\n return true; \n }\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int r = maze.size();\n int c = maze[0].size();\n queue<vector<int>>q;\n q.push({0,entrance[0],entrance[1]});\n int time,ei,ej;\n vector<vector<int>>vis(r,(vector<int>(c,false)));\n while(q.size()){\n vector<int>tt = q.front();\n ei = tt[1];\n ej = tt[2];\n time = tt[0];\n q.pop();\n if(isExit(ei,ej,r,c)){\n if((entrance[0]!=ei or entrance[1]!=ej))\n return time;\n }\n if(isSafe(ei+1,ej,r,c) and !vis[ei+1][ej] and maze[ei+1][ej]!=\'+\'){\n vis[ei+1][ej]=true;\n q.push({time+1,ei+1,ej});\n }\n if(isSafe(ei-1,ej,r,c) and !vis[ei-1][ej] and maze[ei-1][ej]!=\'+\'){\n vis[ei-1][ej]=true;\n q.push({time+1,ei-1,ej});\n }\n if(isSafe(ei,ej+1,r,c) and !vis[ei][ej+1] and maze[ei][ej+1]!=\'+\'){\n vis[ei][ej+1]=true;\n q.push({time+1,ei,ej+1});\n }\n if(isSafe(ei,ej-1,r,c) and !vis[ei][ej-1] and maze[ei][ej-1]!=\'+\'){\n vis[ei][ej-1]=true;\n q.push({time+1,ei,ej-1});\n }\n }\n return -1;\n }\n};\n``` | 5 | 1 | [] | 1 |
nearest-exit-from-entrance-in-maze | C++ Easy DFS+Memoization | c-easy-dfsmemoization-by-vaibhtan1997-jqtm | ```\nclass Solution {\npublic:\n vector> dp;\n \n bool isExit(int i,int j,int m,int n,vector& entrance)\n {\n //Exit lies at the edges of the | vaibhtan1997 | NORMAL | 2021-07-10T16:33:08.988287+00:00 | 2021-07-11T08:00:21.710994+00:00 | 384 | false | ```\nclass Solution {\npublic:\n vector<vector<long int>> dp;\n \n bool isExit(int i,int j,int m,int n,vector<int>& entrance)\n {\n //Exit lies at the edges of the maze and entrance can\'t be the exit\n if(i!=entrance[0]||j!=entrance[1])\n {\n if(i==0||j==0||i==m-1||j==n-1)\n return true;\n }\n \n return false;\n }\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n \n int m = maze.size();\n int n = maze[0].size();\n \n dp.resize(m,vector<long int>(n,-1));\n int i = entrance[0];\n int j = entrance[1];\n \n \n \n long int res = dfs(i,j,m,n,maze,entrance);\n \n \n //If we are able to reach the exit then print the minumum no. of steps else -1\n return res>=INT_MAX ? -1 : res;\n \n \n \n }\n \n long int dfs(int i,int j,int m,int n,vector<vector<char>>& maze,vector<int>& entrance)\n {\n if(i<0||j<0||i>m-1||j>n-1||maze[i][j]==\'+\')\n return INT_MAX;//since we can\'t reach such cells\n \n if(dp[i][j]!=-1)\n return dp[i][j];\n \n if(isExit(i,j,m,n,entrance))\n {\n \n return dp[i][j] = 0;\n }\n \n maze[i][j] = \'+\'; //mark this as visited\n \n //The order of visiting the neighbouring cells is fixed\n\t\tlong int temp = 1+min({dfs(i+1,j,m,n,maze,entrance), dfs(i-1,j,m,n,maze,entrance),dfs(i,j+1,m,n,maze,entrance),dfs(i,j-1,m,n,maze,entrance)});\n \n maze[i][j] = \'.\';//dfs call ended for cell(i,j)\n \n return dp[i][j] = temp;\n }\n}; | 5 | 3 | [] | 4 |
nearest-exit-from-entrance-in-maze | Python BFS solution | python-bfs-solution-by-savikx-eveb | \nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n m, n = len(maze), len(maze[0])\n node = tuple(e | savikx | NORMAL | 2021-07-10T16:11:41.203956+00:00 | 2021-07-10T16:27:49.850296+00:00 | 430 | false | ```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n m, n = len(maze), len(maze[0])\n node = tuple(entrance)\n q = deque([node])\n level = 0\n visited = set([node])\n while q:\n for _ in range(len(q)):\n i, j = q.popleft()\n if (i != entrance[0] or j != entrance[1]) and (i == 0 or j == 0 or i == m - 1 or j == n - 1):\n return level\n for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if 0 <= x < m and 0 <= y < n and maze[x][y] == \'.\' and (x, y) not in visited:\n q.append((x, y))\n visited.add((x, y))\n level += 1\n return -1\n``` | 5 | 0 | ['Breadth-First Search', 'Python'] | 0 |
nearest-exit-from-entrance-in-maze | easy simple solution | easy-simple-solution-by-harithe_curious_-9w3q | please up vote :)Code | hariTHE_CURIOUS_CODER | NORMAL | 2025-01-02T08:37:52.746098+00:00 | 2025-01-02T08:37:52.746098+00:00 | 524 | false | please up vote :)
# Code
```cpp []
class Solution {
public:
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
int dir[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
int m = maze.size();
int n = maze[0].size();
int moves = 1 ;
queue<pair<int,int>> q ;
q.push({entrance[0], entrance[1]});
while(!q.empty()){
int sz = q.size();
while(sz--){
auto curr = q.front();
q.pop();
for(auto it : dir){
int x = curr.first+it[0];
int y = curr.second+it[1];
if(x >=0 && x<m && y>= 0 && y<n && maze[x][y] != '+'){
if(x == 0 || x == m-1 || y==0 || y == n-1){
if(!(x == entrance[0] && y == entrance[1])){
return moves ;
}
}
q.push({x,y});
maze[x][y] = '+';
}
}
}
moves++ ;
}
return - 1;
}
};
```

| 4 | 0 | ['C++'] | 0 |
nearest-exit-from-entrance-in-maze | Detailed Solution for beginners 🤗🤗🤗🤗 | detailed-solution-for-beginners-by-utkar-5gp3 | Welcome, I hope you will have a wonderfull day \uD83E\uDD17\uD83E\uDD17\uD83E\uDD17\uD83E\uDD17\n\nNow, on to the Solution \u23ED\uFE0F\n# Approach\n\n1. Define | utkarshpriyadarshi5026 | NORMAL | 2024-05-08T12:00:06.266168+00:00 | 2024-05-08T12:00:06.266194+00:00 | 377 | false | # Welcome, I hope you will have a wonderfull day \uD83E\uDD17\uD83E\uDD17\uD83E\uDD17\uD83E\uDD17\n\nNow, on to the Solution \u23ED\uFE0F\n# Approach\n\n1. **Define a Helper Class for Coordinates**\nWe begin by defining a helper class Cord to store the coordinates (`x` and `y`), as well as the distance from the entrance (`distFromEntrance`). This helps in easily managing queue operations for the BFS algorithm.\n\n ```\n class Cord {\n int x;\n int y;\n int distFromEntrance;\n\n public Cord(int x, int y, int distFromEntrance) {\n this.x = x;\n this.y = y;\n this.distFromEntrance = distFromEntrance;\n }\n }\n ```\n\n\n2. **Initialize BFS Components**\nWe set up the BFS using a queue to explore the maze, starting from the entrance. We also mark the entrance to prevent revisiting.\n\n\n ```\n Queue<Cord> pathToExit = new ArrayDeque<>();\n // Start BFS from the entrance\n pathToExit.add(new Cord(entrance[0], entrance[1], 0)); \n ```\n\n3. **Explore the Maze Using BFS**\nWe use BFS to explore each possible path \uD83D\uDEE3\uFE0F from the entrance until an exit is found. We check all four possible directions (up, down, left, right) at each step. If the current cell is an exit (not \u274C the entrance), the shortest path length is returned.\n\n```\nwhile (!pathToExit.isEmpty()) {\n \n // Dequeue the current position for exploration\n Cord curr = pathToExit.poll(); \n boolean isExit = (curr.x == 0 || curr.x == rows - 1 || curr.y == 0 || curr.y == cols - 1)\n && !(curr.x == entrance[0] && curr.y == entrance[1]);\n\n // Check if current position is an exit\n if (isExit) return curr.distFromEntrance; \n\n for (int[] dir : directions) {\n int newX = curr.x + dir[0];\n int newY = curr.y + dir[1];\n\n boolean isOutside = newX < 0 || newX >= rows || newY < 0 || newY >= cols;\n\n // Skip if it\'s outside the maze bounds or a wall\n if (isOutside || maze[newX][newY] == \'+\') continue; \n\n\n // Mark the cell as visited by setting it as a wall\n maze[newX][newY] = \'+\'; \n pathToExit.add(new Cord(newX, newY, curr.distFromEntrance + 1));\n }\n}\n```\n\n\n\n# Complexity\n- **Time complexity:**\n$$O(n * m)$$ - The time complexity of this solution is `O(n * m)`, where `n` is the number of rows and `m` is the number of columns in the `maze`. This complexity arises from the breadth-first search (BFS) approach used in the solution, which in the worst case \uD83E\uDD28 might explore every cell in the maze once.\n\n- **Space complexity:**\n$$O(n * m)$$ - In the worst-case \uD83E\uDD28 scenario, the queue could theoretically hold a significant portion of the maze\'s cells at the same time, especially if many cells are reachable and processed at roughly the same depth level in the BFS.\n\n# Code\n```\nclass Solution {\n class Cord {\n int x;\n int y;\n int distFromEntrance;\n\n public Cord(int x, int y, int distFromEntrance) {\n this.x = x;\n this.y = y;\n this.distFromEntrance = distFromEntrance;\n }\n }\n\n public int nearestExit(char[][] maze, int[] entrance) {\n Queue<Cord> pathToExit = new ArrayDeque<>();\n int rows = maze.length;\n int cols = maze[0].length;\n\n pathToExit.add(new Cord(entrance[0], entrance[1], 0));\n int[][] directions = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };\n\n while (!pathToExit.isEmpty()) {\n Cord curr = pathToExit.poll();\n boolean isExit = curr.x == 0 || curr.x == rows - 1 || curr.y == 0 || curr.y == cols - 1;\n boolean isEntrance = curr.x == entrance[0] && curr.y == entrance[1];\n\n if (isExit && !isEntrance)\n return curr.distFromEntrance;\n\n for (int[] dir : directions) {\n int newX = curr.x + dir[0];\n int newY = curr.y + dir[1];\n\n boolean isOutside = newX < 0 || newX >= rows || newY < 0 || newY >= cols;\n if (isOutside || maze[newX][newY] == \'+\')\n continue;\n\n maze[newX][newY] = \'+\';\n pathToExit.add(new Cord(newX, newY, curr.distFromEntrance + 1));\n }\n }\n return -1;\n }\n}\n``` | 4 | 0 | ['Breadth-First Search', 'Graph', 'Java'] | 1 |
nearest-exit-from-entrance-in-maze | Easy to Understand JS Solution | Detailed Explanation | BFS | easy-to-understand-js-solution-detailed-vw871 | Intuition\nMaybe it\'s all the practice solving graph related problems but when I read this one, I immediately thought BFS from the starting point to the border | pokaru | NORMAL | 2023-11-29T15:48:51.657002+00:00 | 2023-11-29T15:48:51.657025+00:00 | 386 | false | # Intuition\nMaybe it\'s all the practice solving graph related problems but when I read this one, I immediately thought BFS from the starting point to the border of the grid.\n\n# Approach\nStarting at `entrance`. I performed BFS until a reached the border of the maze. `getNeighbors` is a helper method for returning neighboring empty cells to whichever `row/col` combination. `isExit` is a helper method for determining whether I\'m at the edge of the maze or not (excluding `entrance` if it happens to start on the border of the maze).\n\nI would have created corresponding 2D array called `visited` to keep track of the nodes I\'ve visited during the BFS traversal but to save space I just reused `maze`. Visited positions were marked with a `1`.\n\nI hope this explanation is clear and helps someone. :)\n\n# Complexity\n- Time complexity:\nO(V + E)\n\n- Space complexity:\nO(V)\n\n# Code\n```\nlet nearestExit = (maze, entrance) => {\n const EMPTY = ".", WALL = "+";\n let getNeighbors = (row,col) => {\n let neighbors = [];\n let shifts = [[0,1],[0,-1],[1,0],[-1,0]];\n let inBounds = (row, col) => row >= 0 && row < maze.length && col >= 0 && col < maze[0].length;\n for (let [rShift,cShift] of shifts) {\n let [nRow,nCol] = [row + rShift, col + cShift];\n if (inBounds(nRow,nCol) && maze[nRow][nCol] !== WALL) neighbors.push([nRow,nCol]);\n }\n return neighbors;\n }\n\n let isExit = (row,col) => {\n let atBorder = (row === 0 || col === 0 || row === maze.length - 1 || col === maze[0].length - 1);\n let notEntrance = !(row === entrance[0] && col === entrance[1]);\n return atBorder && notEntrance;\n }\n\n let count = 0;\n let queue = [entrance];\n maze[entrance[0]][entrance[1]] = 1;\n while (queue.length) {\n let length = queue.length;\n\n for (let i = 0; i < length; i++) {\n let [row,col] = queue.shift();\n if (isExit(row,col)) return count;\n \n let neighbors = getNeighbors(row,col);\n for (let [nRow, nCol] of neighbors) {\n if (maze[nRow][nCol] === EMPTY) {\n maze[nRow][nCol] = 1;\n queue.push([nRow,nCol]);\n }\n }\n }\n count++;\n }\n return -1;\n}\n``` | 4 | 0 | ['Breadth-First Search', 'JavaScript'] | 1 |
nearest-exit-from-entrance-in-maze | JS Graph BFS w/ Intuitive Comments | js-graph-bfs-w-intuitive-comments-by-gno-15nu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | gnoman | NORMAL | 2023-08-23T22:45:11.086908+00:00 | 2023-08-23T22:45:11.086930+00:00 | 370 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {character[][]} maze\n * @param {number[]} entrance\n * @return {number}\n */\nvar nearestExit = function(maze, entrance) {\n //helper function to check if a cell is valid\n let isValid = (row, col) => {\n return row >= 0 && col >= 0 && row < maze.length && col < maze[0].length && maze[row][col] !== \'+\' \n }\n //helper function to determine when we are at an exit\n let isExit = (row, col) => {\n return (row === 0 || col === 0 || row === maze.length - 1 || col === maze[0].length - 1) && maze[row][col] === \'.\' \n}\n //initializing an array to store seen nodes\n let seen = []\n for (let i = 0; i < maze.length; i++) {\n seen.push(new Array(maze[0].length).fill(false))\n }\n //marking the entrance as seen\n seen[entrance[0]][entrance[1]] = true\n //initializing our entrance node in the queue\n let queue = [entrance]\n let dir = [[0,1], [1, 0], [-1, 0], [0, -1]]\n let steps = 0\n\n while (queue.length) {\n let nextQueue = []\n //because our entrance is not an exit, we have to take a step\n steps++\n //for every node in our queue\n for (let i = 0; i < queue.length; i++) {\n //get its row and column\n let [row, col] = queue[i]\n //iterate over the directions of every potential neighbor to check them\n for (const [dx, dy] of dir) {\n let nextRow = row + dx, nextCol = col + dy\n //if a node is valid and we have not seen it, then we: \n if (isValid(nextRow, nextCol) && !seen[nextRow][nextCol]) {\n //see if its an exit -- if it is, return steps\n if (isExit(nextRow, nextCol)){ \n return steps\n } else {\n //otherwise we mark it as seen and push it into the queue so we can check its neighbors\n seen[nextRow][nextCol] = true\n nextQueue.push([nextRow, nextCol])\n }\n }\n }\n\n }\n //reup our queue\n queue = nextQueue\n }\n return -1\n};\n``` | 4 | 0 | ['JavaScript'] | 0 |
nearest-exit-from-entrance-in-maze | simple & easy BFS solution | simple-easy-bfs-solution-by-yash_visavad-nmvt | Code\nPython [0]\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n n, m = len(maze), len(maze[0])\n | yash_visavadia | NORMAL | 2023-07-29T14:46:58.336606+00:00 | 2023-07-29T14:46:58.336630+00:00 | 712 | false | # Code\n``` Python [0]\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n n, m = len(maze), len(maze[0])\n \n q = []\n q.append([entrance[0], entrance[1]])\n \n ans = 0\n while q:\n temp = q.copy()\n q.clear()\n size = len(temp)\n\n for curr in temp:\n i, j = curr\n \n if ans > 0 and (i + 1 == n or i - 1 == -1 or j + 1 == m or j - 1 == -1):\n return ans\n if i + 1 < n and maze[i + 1][j] == \'.\':\n q.append([i + 1, j])\n maze[i + 1][j] = \'+\'\n if i - 1 >= 0 and maze[i - 1][j] == \'.\':\n q.append([i - 1, j])\n maze[i - 1][j] = \'+\'\n if j + 1 < m and maze[i][j + 1] == \'.\':\n q.append([i, j + 1])\n maze[i][j + 1] = \'+\'\n if j - 1 >= 0 and maze[i][j - 1] == \'.\':\n q.append([i, j - 1])\n maze[i][j - 1] = \'+\'\n maze[i][j] = \'+\'\n ans += 1\n return -1\n\n\n``` | 4 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'Python3'] | 1 |
nearest-exit-from-entrance-in-maze | Easy to Understand Code in C++ with explanation | easy-to-understand-code-in-c-with-explan-w13w | Approach\nIt is a simple BFS solution in which we are storing pair of indexes and its length from start in a queue and also a visited array to take care we not | kingp | NORMAL | 2022-12-26T06:36:56.465385+00:00 | 2022-12-26T06:37:15.919599+00:00 | 111 | false | # Approach\nIt is a simple BFS solution in which we are storing pair of indexes and its length from start in a queue and also a visited array to take care we not again go to the same path and if we reach at the edge then we have to return the length.. \nBelow is my C++ code with 95% runtime\n\n\n# Code\n```\nclass Solution {\npublic:\n\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n queue<pair<pair<int,int>,int>> q;\n int n=maze.size();\n int m=maze[0].size();\n int x1=entrance[0];\n int y1=entrance[1];\n q.push({{x1,y1},0});\n int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};\n vector<vector<bool>> visited(n+1,vector<bool>(m+1,false));\n while(!q.empty()){\n pair<int,int> p=q.front().first;\n int x=p.first;\n int y=p.second;\n visited[x][y]=true;\n int len=q.front().second;\n q.pop();\n for(int i=0;i<4;i++){\n int newx=x+dir[i][0];\n int newy= y+dir[i][1];\n if(newx>=0 && newy>=0 && newx<n && newy<m && maze[newx][newy]==\'.\' && !visited[newx][newy]){\n // cout<<newx<<" "<<newy<<" "<<maze[newx][newy];\n visited[newx][newy]=true;\n q.push({{newx,newy},{len+1}});\n if(newx==0 || newy==0 || newx==n-1 || newy==m-1 ){\n // cout<<newx<<" "<<newy;\n return len+1;\n }\n }\n }\n }\n return -1;\n }\n};\n```\nPlease upvote if u like the solution :) | 4 | 0 | ['Breadth-First Search', 'Graph', 'Queue', 'C++'] | 0 |
nearest-exit-from-entrance-in-maze | Simple Python BFS Solution | simple-python-bfs-solution-by-segnides-izg6 | Intuition\nStart from the entrance, do BFS and expand the search, if we are out of the maze, return the distance travelled\n\n# Approach\n- start from the entra | segnides | NORMAL | 2022-12-11T10:43:26.188723+00:00 | 2022-12-11T10:43:26.188775+00:00 | 456 | false | # Intuition\nStart from the entrance, do BFS and expand the search, if we are out of the maze, return the distance travelled\n\n# Approach\n- start from the entrance of maze\n- expand the search using BFS updating the distance travelled for every cell\n- if we are out of the maze, then return the current distance\n\n# Complexity\n- Time complexity:\nO(m * n) where m and n are the number of rows and columns\n\n- Space complexity:\nsince we used a set to store visited cells, space complexity is O(m * n) where m and n are the number of rows and columns\n\n# Code\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n queue = deque([(entrance[0], entrance[1], 0)])\n visited = set()\n visited.add((entrance[0], entrance[1]))\n m = len(maze)\n n = len(maze[0])\n while queue:\n x, y, d = queue.popleft()\n for i, j in [(x, y - 1), (x - 1, y), (x + 1, y), (x, y + 1)]:\n if 0 <= i < m and 0 <= j < n:\n if (i, j) not in visited and maze[i][j] == ".":\n queue.append((i, j, d + 1))\n visited.add((i, j))\n elif (x, y) != (entrance[0], entrance[1]):\n return d\n return -1\n``` | 4 | 0 | ['Breadth-First Search', 'Python3'] | 0 |
nearest-exit-from-entrance-in-maze | JAVA | 2 solutions | BFS | java-2-solutions-bfs-by-sourin_bruh-2to6 | Please Upvote :D\n##### 1. Using an extra 2D \'visited\' array:\n\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int m | sourin_bruh | NORMAL | 2022-11-21T11:41:37.099647+00:00 | 2022-11-21T11:42:49.598704+00:00 | 247 | false | ### **Please Upvote** :D\n##### 1. Using an extra 2D \'visited\' array:\n```\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int m = maze.length, n = maze[0].length;\n int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n Queue<int[]> q = new LinkedList<>();\n q.offer(new int[]{entrance[0], entrance[1], 0});\n\n boolean[][] visited = new boolean[m][n];\n visited[entrance[0]][entrance[1]] = true;\n\n while (!q.isEmpty()) {\n int[] currPos = q.poll();\n int currRow = currPos[0], currCol = currPos[1], currSteps = currPos[2];\n\n for (int[] d : direction) {\n int nextRow = currRow + d[0];\n int nextCol = currCol + d[1];\n\n if (nextRow >= 0 && nextCol >= 0 && nextRow < m && nextCol < n && \n\t\t\t\t maze[nextRow][nextCol] == \'.\' && !visited[nextRow][nextCol] ) {\n\n if (nextRow == 0 || nextCol == 0 || nextRow == m - 1 || nextCol == n - 1) {\n return currSteps + 1;\n }\n\n visited[nextRow][nextCol] = true;\n q.offer(new int[]{nextRow, nextCol, currSteps + 1});\n }\n }\n }\n\n return -1;\n }\n}\n\n// TC: O(m * n)\n// SC: O(m * n) + O(m * n) => O(m * n)\n```\n\n##### 2. Marking if visited in-place (no extra array):\n```\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int m = maze.length, n = maze[0].length;\n int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n Queue<int[]> q = new LinkedList<>();\n q.offer(new int[]{entrance[0], entrance[1], 0});\n\n maze[entrance[0]][entrance[1]] = \'+\';\n\n while (!q.isEmpty()) {\n int[] currPos = q.poll();\n int currRow = currPos[0], currCol = currPos[1], currSteps = currPos[2];\n\n for (int[] d : direction) {\n int nextRow = currRow + d[0];\n int nextCol = currCol + d[1];\n\n if (nextRow >= 0 && nextCol >= 0 && nextRow < m && nextCol < n \n\t\t\t\t && maze[nextRow][nextCol] == \'.\') {\n\n if (nextRow == 0 || nextCol == 0 || nextRow == m - 1 || nextCol == n - 1) {\n return currSteps + 1;\n }\n\n maze[nextRow][nextCol] = \'+\';\n q.offer(new int[]{nextRow, nextCol, currSteps + 1});\n }\n }\n }\n\n return -1;\n }\n}\n\n// TC: O(m * n), SC: O(m * n)\n``` | 4 | 0 | ['Breadth-First Search', 'Queue', 'Java'] | 0 |
nearest-exit-from-entrance-in-maze | Rust BFS | rust-bfs-by-xiaoping3418-zajq | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | xiaoping3418 | NORMAL | 2022-11-21T00:28:37.253521+00:00 | 2022-11-21T00:28:37.253567+00:00 | 742 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N}\n# Code\n```\nimpl Solution {\n pub fn nearest_exit(maze: Vec<Vec<char>>, entrance: Vec<i32>) -> i32 {\n let mut maze = maze;\n let (m, n) = (maze.len(), maze[0].len());\n \n let mut q = vec![(entrance[0] as usize, entrance[1] as usize)];\n let dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n \n maze[entrance[0] as usize][entrance[1] as usize] = \'+\';\n let mut ret = 0;\n\n while q.is_empty() == false {\n let mut temp = vec![];\n ret += 1;\n for (u, v) in q {\n for d in dirs {\n let (x, y) = (u as i32 + d[0], v as i32 + d[1]);\n if x < 0 || x == m as i32 || y < 0 || y == n as i32 { continue }\n\n let (x, y) = (x as usize, y as usize);\n if maze[x][y] == \'+\' { continue }\n \n if x == 0 || x == m - 1 || y == 0 || y == n - 1 { return ret }\n \n maze[x][y] = \'+\';\n temp.push((x, y));\n }\n }\n q = temp;\n }\n \n -1\n }\n}\n``` | 4 | 0 | ['Rust'] | 0 |
nearest-exit-from-entrance-in-maze | C++ || EASY || BFS | c-easy-bfs-by-segfault_00-5p7w | \nclass Solution {\npublic:\n int dx[4] = {1 , -1, 0 ,0};\n int dy[4] = { 0 ,0 , -1 ,1};\n int nearestExit(vector<vector<char>>& maze, vector<int>& ent | segfault_00 | NORMAL | 2022-06-19T17:42:30.787507+00:00 | 2022-06-19T17:52:07.057287+00:00 | 259 | false | ```\nclass Solution {\npublic:\n int dx[4] = {1 , -1, 0 ,0};\n int dy[4] = { 0 ,0 , -1 ,1};\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n \n int n = maze.size() , m = maze[0].size();\n queue<pair<int , int >> q;\n vector<vector<bool>> visited(n , vector<bool>(m,0));\n visited[entrance[0]][entrance[1]] = 1;\n q.push({entrance[0] , entrance[1]});\n int level = 0;\n while( !q.empty() ) {\n int siz = q.size();\n level++;\n while( siz-- ) {\n pair<int , int > p = q.front();\n q.pop();\n for( int i=0; i<4; i++ ){\n int n_r = p.first+dx[i], n_c = p.second+dy[i];\n if( n_r>=0 && n_c>=0 && n_r<n && n_c<m && maze[n_r][n_c]==\'.\' && !visited[n_r][n_c]){\n if( n_r == 0 || n_c==0 || n_r == n-1 || n_c == m-1) return level;\n visited[n_r][n_c] = 1;\n q.push({n_r, n_c});\n }\n }\n }\n }\n return -1;\n }\n};\n``` | 4 | 0 | ['Breadth-First Search', 'Graph', 'Queue', 'C', 'Matrix'] | 0 |
nearest-exit-from-entrance-in-maze | Beats 100% BFS Solution in Python with Explanation! | beats-100-bfs-solution-in-python-with-ex-eup3 | Approach: Breadth-First Search (BFS)Problem Breakdown
Given amazerepresented as a 2D grid, where:
.represents open paths.
+represents walls.
We start at a giv | jxmils | NORMAL | 2025-02-19T21:08:40.499057+00:00 | 2025-02-19T21:08:40.499057+00:00 | 642 | false | ### `Approach: Breadth-First Search (BFS)`
#### `Problem Breakdown`
- Given a `maze` represented as a 2D grid, where:
- `.` represents open paths.
- `+` represents walls.
- We start at a given `entrance` and must find the shortest path to the nearest exit.
- An exit is any open cell `.` on the boundary of the grid, except for the entrance itself.
---
### `Approach & Optimization`
1. `Use Breadth-First Search (BFS) for Shortest Path`
- BFS is optimal for finding the shortest distance in unweighted graphs like this maze.
- A `queue` is used to explore all possible moves level by level.
2. `Mark Cells as Visited In-Place`
- Instead of using a `visited` set, mark visited cells directly in `maze` with `+`.
- This saves `O(n * m)` space, making it more memory-efficient.
3. `Exit Detection`
- If a new cell `(new_x, new_y)` is on the boundary and not the entrance, return the current `steps + 1`.
---
### `Time and Space Complexity`
- `Time Complexity: O(n * m)`
- Each cell is processed at most once.
- `Space Complexity: O(n * m)`
- The worst-case queue size stores all cells in the maze.
---
```python
from collections import deque
from typing import List
class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
# Directions for moving in 4 possible ways (down, right, up, left)
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
rows, cols = len(maze), len(maze[0])
x0, y0 = entrance
# Use a queue for BFS with (row, col, steps)
queue = deque([(x0, y0, 0)])
maze[x0][y0] = '+' # Mark entrance as visited to prevent re-visiting
while queue:
x, y, steps = queue.popleft()
# Explore all four directions
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < rows and 0 <= new_y < cols and maze[new_x][new_y] == '.':
# If we reach an exit that is not the entrance
if new_x in [0, rows - 1] or new_y in [0, cols - 1]:
return steps + 1
# Mark cell as visited and add to queue
maze[new_x][new_y] = '+'
queue.append((new_x, new_y, steps + 1))
return -1 # No exit found
``` | 3 | 0 | ['Python3'] | 1 |
nearest-exit-from-entrance-in-maze | Python | BFS | Easy to Understand | Beats 86% | python-bfs-easy-to-understand-beats-86-b-kr7e | Hope my code helps!\n\nBFS -- Beats 86%\n\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n """\n | Coder1918 | NORMAL | 2024-04-01T23:14:09.115400+00:00 | 2024-04-01T23:14:09.115429+00:00 | 860 | false | Hope my code helps!\n\nBFS -- Beats 86%\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n """\n > With BFS, The first exit it comes across is the closest exit\n > Level represents number of steps ahead\n """\n m, n = len(maze), len(maze[0])\n directions = [(1,0), (0,1), (-1,0), (0,-1)]\n \n queue = deque([(*entrance, 0)])\n visited = [[False] * n for _ in range(m)]\n visited[entrance[0]][entrance[1]] = True\n \n while queue:\n i, j, level = queue.popleft()\n \n # Return as soon as the nearest exit is found\n # If the current position is on the edges of the grid, thats our exit.\n if (i in {0, m - 1} or j in {0, n - 1}) and [i, j] != entrance:\n # Level represents the shortest distance from the entrance\n return level \n \n # Iterate through all the directions\n for x, y in directions:\n x, y = x + i, y + j\n # Make sure each neighbour cell is within the boundary and \n # not yet visited and it is an empty cell\n if 0 <= x < m and 0 <= y < n and \\\n not visited[x][y] and maze[x][y] == \'.\':\n queue.append((x, y, level + 1))\n visited[x][y] = True\n\n return -1\n```\n | 3 | 0 | ['Breadth-First Search', 'Graph', 'Python3'] | 1 |
nearest-exit-from-entrance-in-maze | Simple C++ solution.. striver type approach ..simple bfs .. | simple-c-solution-striver-type-approach-x4wro | Intuition\n Describe your first thoughts on how to solve this problem. \neverything is explained in code comments\n\n# Approach\n Describe your approach to solv | kalpit04 | NORMAL | 2024-03-28T06:44:02.691667+00:00 | 2024-03-28T06:44:02.691698+00:00 | 314 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\neverything is explained in code comments\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& e) {\n int m=maze.size();\n int n=maze[0].size();\n // queue of pair of pair {steps,{row,col}}\n queue<pair<int,pair<int,int>>> q;\n //starting from intital row and column\n //instead of using visited matrix we can change maze from \'.\' -> \'+\' ...to mark visitec\n\n q.push({0,{e[0],e[1]}});\n // travelling in all 4 directions\n int dr[]={-1,1,0,0};\n int dc[]={0,0,-1,1};\n maze[e[0]][e[1]]=\'+\';\n while(!q.empty()){\n auto it=q.front();\n q.pop();\n \n int steps=it.first;\n int row=it.second.first;\n int col=it.second.second;\n //checking if the row,col is border or not.. \n //steps!=0 check if it was not intial\n if((row==0||col==0||row==m-1||col==n-1)&&steps!=0) {\n cout<<row<<" "<<col<<endl;\n return steps;\n }\n for(int i=0;i<4;i++){\n int nrow=row+dr[i];\n int ncol=col+dc[i];\n if(nrow>=0&&ncol>=0&&nrow<m&&ncol<n&&maze[nrow][ncol]==\'.\'){\n q.push({steps+1,{nrow,ncol}});\n maze[nrow][ncol]=\'+\';\n }\n }\n }\n // couldn\'t find any exit\n return -1;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
nearest-exit-from-entrance-in-maze | fastest solution, beats 100% with an old school trick | fastest-solution-beats-100-with-an-old-s-34w3 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n- I modify maze to mark visited cells\n- I use "loop unrolling" technique | sva7777 | NORMAL | 2023-07-30T14:43:20.896741+00:00 | 2023-07-30T14:50:14.008499+00:00 | 712 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- I modify maze to mark visited cells\n- I use "loop unrolling" technique to look up, down, left, right\n\n\n# Complexity\n- Time complexity:\nBeats 100%\n\n\n- Space complexity:\nBeats 66.3%\n\n# Code\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n len_y = len(maze)-1\n len_x = len(maze[0])-1\n\n if len_x==0 and len_y==0:\n return -1\n\n queue = collections.deque()\n\n\n queue.append((entrance[0],entrance[1]))\n\n maze[entrance[0]][entrance[1]] = 2\n moves=0\n while queue:\n\n for i in range(len(queue)):\n current_y, current_x = queue.popleft()\n\n\n if not (current_x== entrance[1] and current_y== entrance[0]) and (current_y==0 or current_y == len_y or current_x== 0 or current_x ==len_x):\n return moves\n\n\n #up\n if current_y-1>=0 and maze[current_y - 1][current_x] == \'.\':\n queue.append((current_y-1,current_x))\n maze[current_y-1][current_x]=2\n # down\n if current_y+1 <= len_y and maze[current_y + 1][current_x] == \'.\':\n queue.append((current_y + 1, current_x))\n maze[current_y+1][current_x] = 2\n #left\n if current_x-1 >=0 and maze[current_y][current_x-1] == \'.\':\n queue.append((current_y, current_x-1))\n maze[current_y][current_x-1] = 2\n #right\n if current_x+1 <=len_x and maze[current_y][current_x+1] == \'.\':\n queue.append((current_y, current_x+1))\n maze[current_y][current_x+1] = 2\n\n\n moves+=1\n\n return -1\n``` | 3 | 0 | ['Python3'] | 1 |
nearest-exit-from-entrance-in-maze | C++, BFS, clean code | c-bfs-clean-code-by-arif-kalluru-5fic | Code\n\n// BFS\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int m = maze.size(), n = maze[0].si | Arif-Kalluru | NORMAL | 2023-07-27T18:52:32.604491+00:00 | 2023-07-27T18:52:32.604522+00:00 | 191 | false | # Code\n```\n// BFS\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int m = maze.size(), n = maze[0].size(); \n int DIR[][2] = { {0,-1}, {1,0}, {0,1}, {-1,0} };\n // r, c, steps\n queue<array<int, 3>> Q;\n Q.push({ entrance[0], entrance[1], 0 });\n maze[entrance[0]][entrance[1]] = \'+\'; // marked as processed\n\n while (!Q.empty()) {\n auto [r, c, steps] = Q.front(); Q.pop();\n\n // If it\'s boundary && it\'s not entrance\n if ((r == 0 || c == 0 || r == m-1 || c == n-1) && (r != entrance[0] || c != entrance[1]))\n return steps;\n\n for (int i = 0; i < 4; i++) {\n int nr = r + DIR[i][0], nc = c + DIR[i][1];\n if (nr < 0 || nc < 0 || nr >= m || nc >= n || maze[nr][nc] == \'+\')\n continue;\n maze[nr][nc] = \'+\'; // marked as processed\n Q.push({ nr, nc, steps+1 });\n }\n\n }\n\n return -1;\n }\n};\n``` | 3 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'C++'] | 0 |
nearest-exit-from-entrance-in-maze | DFS Solution, Only successful DFS code till now. Explained. | dfs-solution-only-successful-dfs-code-ti-py5x | A question which tells you dfs will not necessarily give you the shortest path. \n*\nMy thinking: Firstly I applied only dfs, it gave me a TLE. Next I tried to | jaiswalshash | NORMAL | 2022-11-22T05:12:42.795653+00:00 | 2022-11-22T05:12:42.795688+00:00 | 780 | false | ### A question which tells you dfs will not necessarily give you the shortest path. \n****\nMy thinking: Firstly I applied only dfs, it gave me a TLE. Next I tried to optimize it using memoization as there could be a possiblity of revisiting a cell multiple times. Final test case was not giving me the correct output, after some analysing the final test case of memoization + dfs, I found out that it was giving the corect output for only dfs. **DFS will not give the shortest path in an unweighted graph like structure** , that\'s the key note. You can have a look over this article [here](hhttps://cs.stackexchange.com/questions/4914/why-cant-dfs-be-used-to-find-shortest-paths-in-unweighted-graphs#:~:text=Assign%20edges%20(s%2Ct),paths%20(in%20general%20graphs).ttp://).\n\nCode :\n\n```\nclass Solution {\n int a, b;\n Integer[][] dp;\n public int nearestExit(char[][] maze, int[] entrance) {\n int i = entrance[0];\n int j = entrance[1];\n a = i;\n b = j;\n dp = new Integer[maze.length + 1][maze[0].length + 1];\n if (maze.length < 20 && maze[0].length < 15) {\n int ans1 = dfs1(maze, i, j);\n if (ans1 >= (int)1e9) return -1;\n return ans1;\n }\n \n else {\n int ans = dfs(maze, i, j);\n if (ans >= (int)1e9) return -1;\n return ans;\n }\n }\n int dfs(char[][] maze, int i, int j) {\n \n if (i < 0 || j < 0 || j >= maze[0].length || i >= maze.length || maze[i][j] == \'+\') return (int)1e9;\n if (dp[i][j] != null) return dp[i][j];\n if ((i == 0 || j == 0 || i == maze.length - 1 || j == maze[0].length - 1) && (maze[i][j] == \'.\') && (i != a || j != b)) return 0;\n\n \n maze[i][j] = \'+\';\n int right = 1 + dfs(maze,i, j + 1);\n int left = 1 + dfs(maze,i, j - 1);\n int up = 1 + dfs(maze,i - 1, j);\n int down = 1 + dfs(maze,i + 1, j);\n maze[i][j] = \'.\';\n return dp[i][j] = Math.min(Math.min(up, down), Math.min(left, right));\n }\n int dfs1(char[][] maze, int i, int j) {\n if (i < 0 || j < 0 || j >= maze[0].length || i >= maze.length || maze[i][j] == \'+\') return (int)1e9;\n\n if ((i == 0 || j == 0 || i == maze.length - 1 || j == maze[0].length - 1) && (maze[i][j] == \'.\') && (i != a || j != b)) return 0;\n \n maze[i][j] = \'+\';\n int right = 1 + dfs1(maze,i, j + 1);\n int left = 1 + dfs1(maze,i, j - 1);\n int up = 1 + dfs1(maze,i - 1, j);\n int down = 1 + dfs1(maze,i + 1, j);\n maze[i][j] = \'.\';\n return Math.min(Math.min(up, down), Math.min(left, right));\n }\n}\n```\n\nThe code itself is very explanatory, but what\'s the keynote is that if you want to try dfs for shortest path type question you might have to brainstorm hard might end up writing code like above, while bfs is short, clean and concise.\n\n*So the bottom line is USE BFS FOR SHORTEST PATH TYPE QUESTIONS !* | 3 | 0 | ['Depth-First Search', 'Java'] | 1 |
nearest-exit-from-entrance-in-maze | 😃 Python BFS Easy with comments | python-bfs-easy-with-comments-by-drbless-frgf | We perform a breadth-first search of the maze, using a queue.\n\n\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int | drblessing | NORMAL | 2022-11-21T20:22:57.149996+00:00 | 2022-11-21T20:22:57.150021+00:00 | 582 | false | We perform a breadth-first search of the maze, using a queue.\n\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n # BFS \n rows, cols = len(maze), len(maze[0])\n \n # Set visited spaces to "+"\n maze[entrance[0]][entrance[1]] = \'+\'\n \n # Process stops in a queue\n queue = collections.deque()\n # Add first stop in queue\n queue.appendleft([entrance[0],entrance[1],0])\n \n # Iterate until queue empty or we reach an exit\n while queue:\n row, col, steps = queue.pop()\n \n # Check each direction breadth first\n for r, c in [[row+1, col], [row-1, col], [row, col+1], [row, col-1]]:\n # Check in bounds and it not a wall\n if 0 <= r < rows and 0 <= c < cols and maze[r][c] == \'.\':\n # Check for exit\n if (r == 0) or (c == 0) or (r == rows - 1) or (c == cols -1):\n return steps+1\n # Add stop to visited \n maze[r][c] = \'+\'\n # BFS, new stops get added at the end of the queue, not the front\n queue.appendleft([r,c,steps+1])\n # No exit found\n return -1\n```\n \n**Please upvote if you found this solution helpful!**\n \n | 3 | 0 | ['Breadth-First Search', 'Queue', 'Python', 'Python3'] | 1 |
nearest-exit-from-entrance-in-maze | C++ || BFS || GOOD EXPLAINED CODE || EASY | c-bfs-good-explained-code-easy-by-batman-rzaj | \n*************************************** DON\'T FORGET TO UPVOTE*****************************************\n\n\nclass Solution {\npublic:\n // APPROACH : BAS | batman14 | NORMAL | 2022-11-21T09:27:29.949314+00:00 | 2022-11-21T09:27:29.949352+00:00 | 171 | false | ```\n*************************************** DON\'T FORGET TO UPVOTE*****************************************\n\n\nclass Solution {\npublic:\n // APPROACH : BASIC APPLIED BFS ALGORITHM\n // T(O)=O(linear) && S(O)=O(linear)\n \n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n \n int n = maze.size();\n int m = maze[0].size();\n int er = entrance[0];\n int ec = entrance[1];\n \n //helping data structures\n vector<vector<bool>> vis(n, vector<bool> (m, false));\n vector<int> drow {0, -1, 0, 1};\n vector<int> dcol {-1, 0, 1, 0};\n \n // queue<steps, (row,col) >\n queue<pair<int,pair<int,int>>> q;\n\n // pushing in entrance cell with steps = 0 \n q.push({0,{er,ec}});\n vis[er][ec] = true;\n \n while(!q.empty()) {\n auto it = q.front();\n q.pop();\n int steps = it.first;\n int r = it.second.first;\n int c = it.second.second;\n \n for(int i=0; i<4; i++) {\n int dr = r+drow[i];\n int dc = c+dcol[i];\n \n //check if its a legal move or not\n if(dr>=0&&dr<n&&dc>=0&&dc<m&&vis[dr][dc]==false&&maze[dr][dc]==\'.\') {\n //exit cell\n if(dr==n-1 || dr==0 || dc==m-1 || dc==0 ) { \n if(dr!=er || dc!=ec ) //checking if its entrance cell \n return steps+1;\n }\n \n q.push({steps+1, {dr,dc}});\n vis[dr][dc]=true;\n }\n }\n }\n \n return -1;\n }\n};\n``` | 3 | 0 | ['Breadth-First Search', 'Graph', 'Queue', 'C', 'C++'] | 0 |
nearest-exit-from-entrance-in-maze | Java Solution Using BFS | java-solution-using-bfs-by-abhai0306-be5h | \n\nclass Pair\n{\n int row;\n int col;\n int steps;\n Pair(int _row , int _col , int _steps)\n {\n this.row = _row;\n this.col = _ | abhai0306 | NORMAL | 2022-11-21T09:11:49.844156+00:00 | 2022-11-21T09:11:49.844193+00:00 | 952 | false | \n```\nclass Pair\n{\n int row;\n int col;\n int steps;\n Pair(int _row , int _col , int _steps)\n {\n this.row = _row;\n this.col = _col;\n this.steps = _steps;\n }\n}\n\nclass Solution \n{\n public int nearestExit(char[][] maze, int[] entrance) \n {\n Queue<Pair> q = new LinkedList<>();\n q.add(new Pair(entrance[0] , entrance[1] , 0));\n int m = maze.length;\n int n = maze[0].length;\n int visited[][] = new int[m][n];\n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(maze[i][j] == \'+\')\n visited[i][j] = 1;\n else\n visited[i][j] = 0;\n }\n }\n \n int arow[] = {1,0,-1,0};\n int acol[] = {0,-1,0,1};\n int ans = -1;\n boolean flag = false;\n \n while(!q.isEmpty())\n {\n int row = q.peek().row;\n int col = q.peek().col;\n int steps = q.peek().steps;\n q.remove();\n visited[row][col] = 1;\n for(int i=0;i<4;i++)\n {\n int nrow = row + arow[i];\n int ncol = col + acol[i];\n if(nrow>=0 && nrow<m && ncol>=0 && ncol<n && visited[nrow][ncol] != 1)\n {\n visited[nrow][ncol] = 1;\n q.add(new Pair(nrow,ncol,steps+1));\n if(ncol==0 || nrow==0 || nrow==m-1 || ncol==n-1) \n {\n flag = true;\n ans = steps+1;\n break;\n }\n }\n }\n \n if(flag == true)\n break;\n }\n \n return ans;\n \n }\n}\n``` | 3 | 0 | ['Breadth-First Search', 'Java'] | 0 |
nearest-exit-from-entrance-in-maze | Python BFS Solution O(n*m) | python-bfs-solution-onm-by-energyboy-ko6q | \nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n \n ROWS, COLS = len(maze), len(maze[0])\n | energyboy | NORMAL | 2022-11-21T08:26:33.694053+00:00 | 2022-11-21T08:26:33.694085+00:00 | 464 | false | ```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n \n ROWS, COLS = len(maze), len(maze[0])\n visited = set()\n queue = deque()\n queue.append((tuple(entrance), 0))\n \n while queue:\n element = queue.popleft()\n \n position = element[0]\n step = element[1]\n \n # Check if this position is invalid.\n if (position[0] < 0 or position[0] > ROWS-1\n or position[1] < 0 or position[1] > COLS-1\n or position in visited or maze[position[0]][position[1]] == \'+\'):\n continue\n \n # Check if this position is the answer.\n if (position[0] == 0 or position[0] == ROWS-1\n or position[1] == 0 or position[1] == COLS-1):\n if step != 0 :\n return step\n visited.add(position) \n queue.append(((position[0]+1, position[1]), step+1))\n queue.append(((position[0], position[1]+1), step+1))\n queue.append(((position[0]-1, position[1]), step+1))\n queue.append(((position[0], position[1]-1), step+1))\n\n return -1\n``` | 3 | 0 | ['Breadth-First Search', 'Queue', 'Python'] | 1 |
nearest-exit-from-entrance-in-maze | USING QUEUE (BFS) | using-queue-bfs-by-saurav9283-isxa | \nclass Solution {\npublic:\n vector<int> rowDir = {-1,1,0,0};\n vector<int> colDir = {0,0,1,-1};\n bool border(vector<vector<char>> &maze , int row , | saurav9283 | NORMAL | 2022-11-21T07:45:42.416626+00:00 | 2022-11-21T07:45:42.416672+00:00 | 33 | false | ```\nclass Solution {\npublic:\n vector<int> rowDir = {-1,1,0,0};\n vector<int> colDir = {0,0,1,-1};\n bool border(vector<vector<char>> &maze , int row , int col)\n {\n if((row == 0) || (row == maze.size()-1))\n {\n return true;\n }\n if((col == 0) || (col == maze[0].size()-1))\n {\n return true;\n }\n return false;\n }\n \n bool validstep(vector<vector<char>> &maze , int &row , int &col)\n {\n int m = maze.size();\n int n = maze[0].size();\n if(row < 0 || row == m || col < 0 || col == n || maze[row][col] == \'+\')\n {\n return false;\n }\n return true;\n }\n \n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) \n {\n queue<pair<int , int>> q; // creating a queue\n q.push({entrance[0] , entrance[1]}); // initially push the entrance location\n int path = 0;\n maze[entrance[0]][entrance[1]] = \'+\'; //mark as visited\n while(!q.empty()) \n {\n int size = q.size();\n while(size--)\n {\n int row = q.front().first;\n int col = q.front().second;\n q.pop();\n for(int direction = 0 ; direction < 4; direction++) // for checking all direction\n {\n int newRow = row + rowDir[direction]; // new row \n int newCol = col + colDir[direction];\n if(validstep(maze , newRow , newCol))\n {\n maze[newRow][newCol] = \'+\'; // mark as visited\n if(border(maze , newRow , newCol)) // checking is border or not\n {\n return (path + 1); // if it is border then retuern\n }\n else\n {\n q.push({newRow , newCol}); // if not a border then push in queue to next BFS from this\n }\n }\n }\n }\n path++;\n }\n return -1;\n }\n};\n\n\n``` | 3 | 0 | ['C'] | 0 |
nearest-exit-from-entrance-in-maze | ✅ EZ Python || BFS | ez-python-bfs-by-0xsapra-5bvf | \nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n """\n . entrace cant be termed as exit cell | 0xsapra | NORMAL | 2022-11-21T07:18:26.303844+00:00 | 2022-11-21T07:18:26.303879+00:00 | 769 | false | ```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n """\n . entrace cant be termed as exit cell\n """\n \n seen = set()\n exits = set()\n R, C = len(maze), len(maze[0])\n entrance = tuple(entrance)\n \n for r in range(R):\n if maze[r][0] == ".":\n exits.add((r, 0))\n if maze[r][C-1] == ".":\n exits.add((r, C-1))\n \n for c in range(C):\n if maze[0][c] == ".":\n exits.add((0, c))\n if maze[R-1][c] == ".":\n exits.add((R-1, c))\n \n if entrance in exits:\n exits.remove(entrance)\n \n \n \n q = [(entrance, 0)] # start, distance\n \n \n while q:\n curr_pos , d = q.pop(0)\n \n if curr_pos in exits:\n return d\n \n if curr_pos in seen:\n continue\n \n seen.add(curr_pos)\n \n \n for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n nx = dx + curr_pos[0]\n ny = dy + curr_pos[1]\n \n if 0 <= nx < R and 0 <= ny < C and maze[nx][ny] == ".":\n q.append(((nx, ny), d + 1))\n \n \n return -1\n``` | 3 | 0 | ['Python'] | 0 |
nearest-exit-from-entrance-in-maze | Beginner Friendly Standard BFS [8ms] | beginner-friendly-standard-bfs-8ms-by-cr-383d | class Solution {\n\n public int nearestExit(char[][] maze, int[] entrance) {\n int rows = maze.length, cols = maze[0].length;\n \n Queue | crusifixx | NORMAL | 2022-11-21T05:09:19.911703+00:00 | 2022-11-21T05:09:19.911744+00:00 | 10 | false | class Solution {\n\n public int nearestExit(char[][] maze, int[] entrance) {\n int rows = maze.length, cols = maze[0].length;\n \n Queue<int[]> queue = new LinkedList<>();\n boolean[][] visited = new boolean[rows][cols];\n \n int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}}; //directions array\n int x, y;\n int steps = 0; //intializing steps \n \n queue.offer(entrance); //adding the entracne coordinates to the bfs queue\n visited[entrance[0]][entrance[1]] = true; //marking the entrance as visited\n \n while (!queue.isEmpty()) {\n int queueSize = queue.size(); \n steps++; //incrementing the steps as we proceed with bfs\n \n for (int i=0;i<queueSize;i++) {\n int[] curr = queue.poll(); //polling from the queue\n \n for (int[] dir: dirs) { //perfoming standard bfs\n x = dir[0]+curr[0]; \n y = dir[1]+curr[1];\n \n //base condition\n if (x<0||x>=rows||y<0||y>=cols) continue;\n \n //skip if we encounter a wall or if the cell is already visited\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}); //we found a new valid coordinate so add it to the queue\n visited[x][y] = true; //mark its visited as true\n }\n }\n }\n \n return -1; //if there are no exits we return -1\n }\n} | 3 | 0 | ['Breadth-First Search'] | 0 |
nearest-exit-from-entrance-in-maze | ✅ JS || Multiple Approaches || Easy to understand | js-multiple-approaches-easy-to-understan-964a | I just found this Blog and Github repository with solutions to Leetcode problems.\nhttps://leet-codes.blogspot.com/2022/11/nearest-exit-from-entrance-in-maze.ht | pmistry_ | NORMAL | 2022-11-21T03:59:47.954485+00:00 | 2022-11-21T03:59:47.954528+00:00 | 1,634 | false | I just found this Blog and Github repository with solutions to Leetcode problems.\nhttps://leet-codes.blogspot.com/2022/11/nearest-exit-from-entrance-in-maze.html\nIt has solutions to almost every problem on Leetcode, and I recommend checking it out.\nNote: You can bookmark it as a resource, and approach. Other approaches are in above blog\n<br>\n\n```\n/**\n * @param {character[][]} maze\n * @param {number[]} entrance\n * @return {number}\n */\nconst dx = [1, -1, 0, 0], dy = [0, 0, 1, -1];\nconst nearestExit = (g, entrance) => {\n let [n, m, ex, ey] = [g.length, g[0].length, entrance[0], entrance[1]];\n let dis = initialize2DArrayNew(n, m);\n let q = [];\n for (let i = 0; i < n; i++) { // find all exits\n for (let j = 0; j < m; j++) {\n if ((i == ex && j == ey) || g[i][j] == \'+\') continue;\n if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {\n q.push([i, j]);\n dis[i][j] = 0; // reset to 0 for calculating the min path\n }\n }\n }\n while (q.length) { // bfs\n let cur = q.shift();\n let [x, y] = cur;\n for (let k = 0; k < 4; k++) {\n let xx = x + dx[k];\n let yy = y + dy[k];\n if (xx < 0 || xx >= n || yy < 0 || yy >= m || g[xx][yy] == \'+\') continue; // out of bound or wall\n if (dis[xx][yy] > dis[x][y] + 1) { // update min path\n dis[xx][yy] = dis[x][y] + 1;\n q.push([xx, yy]);\n }\n }\n }\n let res = dis[ex][ey];\n return res == Number.MAX_SAFE_INTEGER ? -1 : res;\n};\n\nconst initialize2DArrayNew = (n, m) => { \n let data = []; \n for (let i = 0; i < n; i++) { \n let tmp = Array(m).fill(Number.MAX_SAFE_INTEGER); \n data.push(tmp); \n } \n return data; \n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
nearest-exit-from-entrance-in-maze | CPP | Faster than O(n^2) | Easy to Read | cpp-faster-than-on2-easy-to-read-by-bhal-xm6b | 1926. Nearest Exit from Entrance in Maze\n#\n# CPP Code\n\nclass Solution {\npublic:\n \n vector<int> dx = {-1, 0, 1, 0};\n vector<int> dy = {0, 1, 0, | bhalerao-2002 | NORMAL | 2022-11-21T02:39:51.443107+00:00 | 2022-11-21T02:39:51.443153+00:00 | 66 | false | # 1926. Nearest Exit from Entrance in Maze\n#\n# CPP Code\n```\nclass Solution {\npublic:\n \n vector<int> dx = {-1, 0, 1, 0};\n vector<int> dy = {0, 1, 0, -1};\n \n int nearestExit(vector<vector<char>>& a, vector<int>& st) {\n queue<vector<int>> q;\n st.push_back(0);\n q.push(st);\n a[st[0]][st[1]] = \'x\';\n while (!q.empty()) {\n int x = q.front()[0], y = q.front()[1], stp = q.front()[2];\n q.pop();\n for (int dir=0; dir<4; ++dir) {\n int tx=x+dx[dir], ty=y+dy[dir];\n if (tx>=0 && tx<a.size() && ty>=0 && ty<a[0].size() && a[tx][ty]==\'.\') {\n if (tx==0 || tx==a.size()-1 || ty==0 || ty==a[0].size()-1)\n return stp+1;\n q.push({tx, ty, stp+1});\n a[tx][ty] = \'x\';\n }\n }\n }\n return -1;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
nearest-exit-from-entrance-in-maze | C# Queue | c-queue-by-anand9589-g7n5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | anand9589 | NORMAL | 2022-11-21T01:22:05.930360+00:00 | 2022-11-21T01:22:05.930383+00:00 | 526 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n\n public int NearestExit(char[][] maze, int[] entrance)\n {\n int result = -1;\n bool[][] visited = new bool[maze.Length][];\n for (int i = 0; i < maze.Length; i++)\n {\n visited[i] = new bool[maze[i].Length];\n for (int j = 0; j < maze[i].Length; j++)\n {\n if (maze[i][j] == \'+\')\n {\n visited[i][j] = true;\n }\n }\n }\n Queue<(int, int, int)> queue = new();\n\n queue.Enqueue((0, entrance[0], entrance[1]));\n visited[entrance[0]][entrance[1]] = true;\n while (queue.Count > 0)\n {\n (int count, int x, int y) = queue.Dequeue();\n\n if ((x != entrance[0] || y != entrance[1]) && (x == maze.Length - 1 || x == 0 || y == maze[x].Length - 1 || y == 0)) return count;\n\n count++;\n //top y-1\n CheckCoordinatesAndEnqueue(maze, queue, visited, count, x, y-1);\n\n //bottom y+1\n CheckCoordinatesAndEnqueue(maze, queue, visited, count, x, y+1);\n\n //left x-1\n CheckCoordinatesAndEnqueue(maze, queue, visited, count, x-1, y);\n\n //right x+1\n CheckCoordinatesAndEnqueue(maze, queue, visited, count, x+1, y);\n }\n\n return result;\n }\n\n private void CheckCoordinatesAndEnqueue(char[][] maze, Queue<(int, int, int)> queue, bool[][] visited, params int[] arr)\n {\n int count = arr[0];\n int x = arr[1];\n int y = arr[2];\n\n if (x >= 0 && x < maze.Length && y >= 0 && y < maze[x].Length && !visited[x][y])\n {\n queue.Enqueue((count, x, y));\n visited[x][y] = true;\n }\n }\n \n}\n``` | 3 | 0 | ['C#'] | 1 |
nearest-exit-from-entrance-in-maze | Golang | BFS | golang-bfs-by-yfw13-ke4s | \ntype State struct {\n r, c, l int\n}\n\nfunc nearestExit(maze [][]byte, entrance []int) int {\n m, n := len(maze), len(maze[0])\n q := []State{{entra | tw13 | NORMAL | 2022-11-21T00:38:30.215836+00:00 | 2022-11-21T00:38:30.215899+00:00 | 414 | false | ```\ntype State struct {\n r, c, l int\n}\n\nfunc nearestExit(maze [][]byte, entrance []int) int {\n m, n := len(maze), len(maze[0])\n q := []State{{entrance[0], entrance[1], 0}}\n v := make(map[State]struct{})\n var state, vState State\n var rr, cc int\n d4 := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}\n \n for len(q) > 0 {\n state, q = q[0], q[1:]\n \n vState = State{state.r, state.c, 0}\n if _, ok := v[vState]; ok {\n continue\n }\n v[vState] = struct{}{}\n \n if (state.r == 0 || state.r == m-1 || state.c == 0 || state.c == n-1) && (state.r != entrance[0] || state.c != entrance[1]) {\n return state.l\n }\n \n for _, d := range d4 {\n rr, cc = state.r + d[0], state.c + d[1]\n if rr >= 0 && rr < m && cc >= 0 && cc < n && maze[rr][cc] == \'.\' {\n q = append(q, State{rr, cc, state.l+1})\n }\n }\n \n }\n \n return -1\n}\n``` | 3 | 0 | ['Go'] | 0 |
nearest-exit-from-entrance-in-maze | C | 105ms(100%) & 7.4MB(100%) | BFS & Link list | c-105ms100-74mb100-bfs-link-list-by-peih-f32j | Intuition\n Describe your first thoughts on how to solve this problem. \nUsing BFS by link list\n# Approach\n Describe your approach to solving the problem. \n1 | peihao61 | NORMAL | 2022-11-21T00:33:18.947888+00:00 | 2022-11-21T08:05:20.968560+00:00 | 509 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing BFS by link list\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Start from entrance and add link list\n2. Find next empty cells, \'.\', until the exit\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nstruct MazeRecord\n{\n char cRow;\n char cCol;\n short sDistance;\n\n struct MazeRecord* pstNext;\n};\n\nstruct MazeRecord* AddMazeRecord(struct MazeRecord* pstTail, char cRow, char cCol, short sDistance)\n{\n if(pstTail->pstNext)\n {\n pstTail = pstTail->pstNext;\n }\n else\n {\n pstTail->pstNext = (struct MazeRecord*) malloc(sizeof(struct MazeRecord));\n pstTail = pstTail->pstNext;\n pstTail->pstNext = NULL;;\n }\n\n pstTail->cRow = cRow;\n pstTail->cCol = cCol;\n pstTail->sDistance = sDistance;\n\n return pstTail;\n}\n\nint nearestExit(char** maze, int mazeSize, int* mazeColSize, int* entrance, int entranceSize){\n char cMazeSize = mazeSize - 1, cMazeColSize = *mazeColSize - 1;\n\n struct MazeRecord* pstHead = (struct MazeRecord*) malloc(sizeof(struct MazeRecord));\n pstHead->cRow = *entrance;\n pstHead->cCol = *(entrance + 1);\n pstHead->sDistance = 0;\n pstHead->pstNext = NULL;\n maze[pstHead->cRow][pstHead->cCol] = \',\';\n\n short sRet = 0;\n struct MazeRecord* pstTail = pstHead;\n while(pstHead)\n {\n // check up\n if(pstHead->cRow && maze[pstHead->cRow-1][pstHead->cCol] == \'.\')\n {\n if(pstHead->cRow-1 == 0 || pstHead->cCol == 0 || pstHead->cCol == cMazeColSize)\n {\n sRet = pstHead->sDistance + 1;\n break;\n }\n else\n {\n maze[pstHead->cRow-1][pstHead->cCol] = \',\';\n pstTail = AddMazeRecord(pstTail, pstHead->cRow-1, pstHead->cCol, pstHead->sDistance+1);\n }\n }\n\n // check left\n if(pstHead->cCol && maze[pstHead->cRow][pstHead->cCol-1] == \'.\')\n {\n if(pstHead->cCol-1 == 0 || pstHead->cRow == 0 || pstHead->cRow == cMazeSize)\n {\n sRet = pstHead->sDistance + 1;\n break;\n }\n else\n {\n maze[pstHead->cRow][pstHead->cCol-1] = \',\';\n pstTail = AddMazeRecord(pstTail, pstHead->cRow, pstHead->cCol-1, pstHead->sDistance+1);\n }\n }\n\n // check right\n if(pstHead->cCol < cMazeColSize && maze[pstHead->cRow][pstHead->cCol+1] == \'.\')\n {\n if(pstHead->cCol+1 == cMazeColSize || pstHead->cRow == 0 || pstHead->cRow == cMazeSize)\n {\n sRet = pstHead->sDistance + 1;\n break;\n }\n else\n {\n maze[pstHead->cRow][pstHead->cCol+1] = \',\';\n pstTail = AddMazeRecord(pstTail, pstHead->cRow, pstHead->cCol+1, pstHead->sDistance+1);\n }\n }\n\n // check down\n if(pstHead->cRow < cMazeSize && maze[pstHead->cRow+1][pstHead->cCol] == \'.\')\n {\n if(pstHead->cRow+1 == cMazeSize || pstHead->cCol == 0 || pstHead->cCol == cMazeColSize)\n {\n sRet = pstHead->sDistance + 1;\n break;\n }\n else\n {\n maze[pstHead->cRow+1][pstHead->cCol] = \',\';\n pstTail = AddMazeRecord(pstTail, pstHead->cRow+1, pstHead->cCol, pstHead->sDistance+1);\n }\n }\n\n if(pstHead == pstTail) break;\n\n struct MazeRecord* pstTmp = pstHead;\n pstHead = pstHead->pstNext;\n pstTmp->pstNext = pstTail->pstNext;\n pstTail->pstNext = pstTmp;\n }\n\n while(pstHead)\n {\n pstTail = pstHead;\n pstHead = pstHead->pstNext;\n free(pstTail);\n }\n\n return sRet? sRet: -1;\n}\n``` | 3 | 0 | ['C'] | 0 |
nearest-exit-from-entrance-in-maze | Simple java solution | simple-java-solution-by-siddhant_1602-1o9x | ```\nclass Solution {\n public int nearestExit(char[][] m, int[] e) {\n int c=0;\n Queue nm=new LinkedList<>();\n int a[][]={{0,1},{1,0} | Siddhant_1602 | NORMAL | 2022-08-03T08:06:24.314349+00:00 | 2022-08-03T08:06:24.314390+00:00 | 219 | false | ```\nclass Solution {\n public int nearestExit(char[][] m, int[] e) {\n int c=0;\n Queue<int[]> nm=new LinkedList<>();\n int a[][]={{0,1},{1,0},{-1,0},{0,-1}};\n nm.offer(e);\n boolean k[][]=new boolean[m.length][m[0].length];\n k[e[0]][e[1]]=true;\n while(!nm.isEmpty())\n {\n int p=nm.size();\n c++;\n for(int i=0;i<p;i++)\n {\n int f[]=nm.poll();\n for(int b[]:a)\n {\n int x=b[0]+f[0];\n int y=f[1]+b[1];\n if(x<0||y<0||x>=m.length||y>=m[0].length)\n continue;\n else if(k[x][y]||m[x][y]==\'+\')\n continue;\n if(x==0||y==0||x==m.length-1||y==m[0].length-1)\n return c;\n nm.add(new int[]{x,y});\n k[x][y]=true;\n }\n }\n }\n return -1;\n }\n} | 3 | 0 | ['Breadth-First Search', 'Java'] | 0 |
nearest-exit-from-entrance-in-maze | Easy BFS Solution With Comments and approach | easy-bfs-solution-with-comments-and-appr-vppc | INTUITION: From the entrance start a bfs for all the four directions and stop if you reach any border cells and they are not walls.\n\nclass Solution {\npublic | karan252 | NORMAL | 2022-07-07T23:59:07.662613+00:00 | 2022-07-07T23:59:07.662640+00:00 | 207 | false | INTUITION: From the entrance start a bfs for all the four directions and stop if you reach any border cells and they are not walls.\n```\nclass Solution {\npublic:\n int dx[4]={0,0,-1,1}; \n int dy[4]={1,-1,0,0};\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int n=maze.size();\n int m=maze[0].size();\n vector<vector<bool>> vis(n,vector<bool>(m,false)); // vis array to keep track of visited cells\n queue<pair<int,int>> q; // Initialising a queue to store indexes\n q.push({entrance[0],entrance[1]});\n vis[entrance[0]][entrance[1]]=true;\n int count=0; \n while(q.empty()==false)\n {\n int sz=q.size();\n count++;\n while(sz--)\n {\n int x=q.front().first;\n int y=q.front().second;\n q.pop();\n for(int idx=0;idx<4;idx++)\n {\n int nx=x+dx[idx];\n int ny=y+dy[idx];\n\t\t\t\t\t// checking if the cell we are traversing to is valid or not such as whether it is within boundary and not a wall\n if(nx>=0 && nx<n && ny>=0 && ny<m && vis[nx][ny]==false && maze[nx][ny]!=\'+\') \n {\n if(nx==0 || nx==n-1 || ny==0 || ny==m-1) // checking if it is a boundary cell an if true we return the count.\n return count;\n q.push({nx,ny});\n vis[nx][ny]=true;\n } \n }\n \n }\n }\n return -1; // if there is no way out return -1\n }\n};\n``` | 3 | 0 | ['Breadth-First Search', 'Queue', 'C', 'C++'] | 1 |
nearest-exit-from-entrance-in-maze | ola ola | ola-ola-by-fr1nkenstein-ri4q | \nclass Solution {\n public int nearestExit(char[][] maze, int[] e) {\n int dx[]={1,-1,0,0};\n int dy[]={0,0,-1,1};\n if(maze[0].length= | fr1nkenstein | NORMAL | 2022-06-02T18:05:36.633710+00:00 | 2022-06-02T18:05:36.633761+00:00 | 54 | false | ```\nclass Solution {\n public int nearestExit(char[][] maze, int[] e) {\n int dx[]={1,-1,0,0};\n int dy[]={0,0,-1,1};\n if(maze[0].length==1&&maze.length==1||maze[e[0]][e[1]]==\'+\')return -1;\n Queue<int[]>p=new LinkedList<>();\n int a[]={e[0],e[1],0};\n p.add(a);\n maze[e[0]][e[1]]=\'+\';\n \n while(!p.isEmpty()){\n\n int b[]=p.poll();\n for(int k=0;k<4;k++){\n int x=b[0]+dx[k];\n int y=b[1]+dy[k];\n if(x<0||y<0||x>=maze.length||y>=maze[0].length||maze[x][y]==\'+\')continue;\n else if(x==0||y==0||x==maze.length-1||y==maze[0].length-1&&maze[x][y]==\'.\'){System.out.println(x+" "+y+"ans");\n return b[2]+1;}\n System.out.println(x+" "+y+" "+ maze[x][y]);\n int z[]={x,y,b[2]+1};\n p.add(z);\n maze[x][y]=\'+\';\n \n }\n \n \n }\n return -1;\n }\n}\n``` | 3 | 0 | [] | 0 |
nearest-exit-from-entrance-in-maze | C++ || BFS || IN-DEPTH Analysis | c-bfs-in-depth-analysis-by-beast_123-mvjl | c++\nFirst I Thought We Have To Find The Nearest Exit Cell Coordinate Manhattan Distance From The Given Position.\nI Solved This Question Keeping The Above Thou | Beast_123 | NORMAL | 2021-10-15T09:14:12.781023+00:00 | 2021-10-15T13:55:35.280773+00:00 | 262 | false | **c++**\nFirst I Thought We Have To Find The Nearest Exit Cell Coordinate Manhattan Distance From The Given Position.\nI Solved This Question Keeping The Above Thought In Mind.\n\nAnd Here\'s The Code \n**Suprisingly It has passed 188 test Cases Out of 194**\n```\nvector<int> dir={-1,0,1,0,-1};\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n queue<pair<int, int>> pq;\n int x = entrance[0], y = entrance[1];\n int n = maze.size(), m = maze[0].size();\n maze[x][y] = \'+\';\n int ans = INT_MAX;\n pq.push({x, y});\n while(!pq.empty()){\n int size = pq.size();\n while(size--){\n auto top = pq.front();\n pq.pop();\n for(int i = 0; i < 4; i++){\n int r = top.first + dir[i];\n int c = top.second + dir[i + 1];\n if(r >= 0 && c >= 0 && r < n && c < m && maze[r][c] != \'+\'){\n pq.push({r, c});\n maze[r][c] = \'+\';\n }\n if(r < 0 || c < 0 || r >= n || c >= m){\n if(top.first != x || top.second != y){\n ans = min(ans , abs(x - top.first) + abs(top.second - y));\n }\n }\n }\n }\n }\n if(ans == INT_MAX) return -1;\n return ans;\n }\n```\n\nNow Comming Back To Original Question :\nWe Actually have to Find the Minimum Number Of Steps Reuired to reach The Nearest Exit:\nFor Which I have to do Small Modification of The Above Code,\nInstead of **queue<pair<int,int>>** I took **queue<pair<pair<int, int>, int>>** Which Will Keep The count OF the Number Of steps Taken So far:\n\nHere\'s The Code:\n```\nclass Solution {\npublic:\n vector<int> dir={-1,0,1,0,-1};\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n queue<pair<pair<int, int>,int>> pq;\n int x = entrance[0], y = entrance[1];\n int n = maze.size(), m = maze[0].size();\n maze[x][y] = \'+\';\n int ans = INT_MAX;\n pq.push({{x, y}, 0});\n while(!pq.empty()){\n int size = pq.size();\n while(size--){\n auto top = pq.front();\n pq.pop();\n for(int i = 0; i < 4; i++){\n int r = top.first.first + dir[i];\n int c = top.first.second + dir[i + 1];\n if(r >= 0 && c >= 0 && r < n && c < m && maze[r][c] != \'+\'){\n pq.push({{r, c}, top.second + 1});\n maze[r][c] = \'+\';\n }\n else if(r < 0 || c < 0 || r >= n || c >= m){\n if(top.first.first != x || top.first.second != y){\n ans = min(ans , top.second);\n }\n }\n }\n }\n }\n if(ans == INT_MAX) return -1;\n return ans;\n }\n};\n\n**Please Do UpVote , It Will BE Very HelpFull.....Thanks**\n``` | 3 | 0 | ['Breadth-First Search', 'C', 'Matrix'] | 0 |
nearest-exit-from-entrance-in-maze | Java Code, faster than 100.00% of Java online submissions. using BFS | java-code-faster-than-10000-of-java-onli-0089 | \n public int nearestExit(char[][] maze, int[] entrance) {\n LinkedList<Integer> que = new LinkedList<>();\n int n = maze.length, m = maze[0]. | vishalgupta171099 | NORMAL | 2021-07-12T05:25:26.747012+00:00 | 2021-07-12T05:25:50.191539+00:00 | 160 | false | ```\n public int nearestExit(char[][] maze, int[] entrance) {\n LinkedList<Integer> que = new LinkedList<>();\n int n = maze.length, m = maze[0].length;\n que.addLast(entrance[0] * m + entrance[1]);\n maze[entrance[0]][entrance[1]] = \'+\';\n int [][]dir = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};\n \n int level = 0;\n \n while(que.size() != 0) {\n int size = que.size();\n \n while(size-->0) {\n int idx = que.removeFirst();\n int sr = idx / m, sc = idx % m;\n \n \n if((sr == 0 || sr == n - 1|| sc == 0 || sc == m - 1) && level != 0) {\n return level;\n }\n \n for(int d = 0; d < 4; d++) {\n int r = sr + dir[d][0];\n int c = sc + dir[d][1];\n \n if(r >= 0 && c >= 0 && r < n && c < m && maze[r][c] == \'.\') {\n maze[r][c] = \'+\';\n que.addLast(r * m + c);\n }\n }\n }\n level++;\n }\n \n return -1;\n }\n``` | 3 | 0 | [] | 0 |
nearest-exit-from-entrance-in-maze | JavaScript and TypeScript Clean Code | javascript-and-typescript-clean-code-by-jabiv | JavaScript:\njs\nconst dir = [[0, 1], [0, -1], [1, 0], [-1, 0]];\nconst WALKED = \'-\', WALL = \'+\', NO_EXIT = -1;\n\n/**\n * @param {character[][]} maze\n * @ | menheracapoo | NORMAL | 2021-07-11T10:32:49.906884+00:00 | 2021-07-11T13:07:14.385784+00:00 | 682 | false | JavaScript:\n```js\nconst dir = [[0, 1], [0, -1], [1, 0], [-1, 0]];\nconst WALKED = \'-\', WALL = \'+\', NO_EXIT = -1;\n\n/**\n * @param {character[][]} maze\n * @param {number[]} entrance\n * @return {number}\n */\nvar nearestExit = function(maze, entrance) {\n const m = maze.length, n = maze[0].length;\n const [ey, ex] = entrance;\n maze[ey][ex] = WALKED;\n \n const queue = new Queue([[ey, ex, 0]]);\n while (queue.size()) {\n const [y, x, step] = queue.dequeue();\n \n for (const [dy, dx] of dir) {\n const ny = y + dy, nx = x + dx, nextStep = step + 1;\n const overBorder = ny < 0 || ny >= m || nx < 0 || nx >= n;\n if (overBorder) {\n continue;\n }\n if (maze[ny][nx] === WALKED || maze[ny][nx] === WALL) {\n continue;\n }\n const isExit = ny === 0 || ny === m - 1 || nx === 0 || nx === n - 1;\n if (isExit) {\n return nextStep;\n }\n \n maze[ny][nx] = WALKED;\n queue.enqueue([ny, nx, nextStep]);\n }\n }\n \n return NO_EXIT;\n};\n\n```\n\nTypeScript:\n```js\nconst dir = [[0, 1], [0, -1], [1, 0], [-1, 0]];\nconst WALKED = \'-\', WALL = \'+\', NO_EXIT = -1;\n\nfunction nearestExit(maze: string[][], entrance: number[]): number {\n const m = maze.length, n = maze[0].length;\n const [ey, ex] = entrance;\n maze[ey][ex] = WALKED;\n \n const queue = new Queue([[ey, ex, 0]]);\n while (queue.size()) {\n const [y, x, step] = queue.dequeue();\n \n for (const [dy, dx] of dir) {\n const ny = y + dy, nx = x + dx, nextStep = step + 1;\n const overBorder = ny < 0 || ny >= m || nx < 0 || nx >= n;\n if (overBorder) {\n continue;\n }\n if (maze[ny][nx] === WALKED || maze[ny][nx] === WALL) {\n continue;\n }\n const isExit = ny === 0 || ny === m - 1 || nx === 0 || nx === n - 1;\n if (isExit) {\n return nextStep;\n }\n \n maze[ny][nx] = WALKED;\n queue.enqueue([ny, nx, nextStep]);\n }\n }\n \n return NO_EXIT;\n};\n\n```\n | 3 | 2 | ['TypeScript', 'JavaScript'] | 2 |
nearest-exit-from-entrance-in-maze | BFS Solution without Vis. Matrix (commented) | bfs-solution-without-vis-matrix-commente-kcik | \nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entry) {\n int n = maze.size(), m = maze[0].size();\n ve | suraj013 | NORMAL | 2021-07-10T16:33:46.421452+00:00 | 2021-07-23T09:42:13.848632+00:00 | 134 | false | ```\nclass Solution {\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entry) {\n int n = maze.size(), m = maze[0].size();\n vector<vector<int>> dist(n, vector <int> (m, 0));\n queue <pair <int, int>> q;\n int i = entry[0], j = entry[1];\n\t\tq.push({i, j}); // insert the entrance\n maze[i][j] = \'+\'; // mark entrance visited\n\t\t\n\t\t// 4 direction\n int dx[] = {-1, 0, 1, 0};\n int dy[] = { 0, 1, 0, -1};\n while(q.size()) {\n int x = q.front().first, y = q.front().second; // current cell\n q.pop();\n \n for(int i = 0; i<4; i++) { // iterate over neighbours\n\t\t\t\tint xi = x+dx[i], yi = y+dy[i]; // current neighbour\n\t\t\t\t\n if(xi >= 0 && xi < n && yi >= 0 && yi < m) { // if not out of the maze\n if(maze[xi][yi] == \'.\') { // if empty\n q.push({xi, yi});\n dist[xi][yi] = dist[x][y] + 1; // increment the dist from entrance\n maze[xi][yi] = \'+\'; // mark visited\n if(xi == 0 || xi == n-1 || yi == 0 || yi == m-1) {\n return dist[xi][yi]; // if on border, return res\n }\n }\n }\n }\n }\n return -1;\n }\n};\n\n// TC: O(n*m)\n// SC: O(n*m)\n``` | 3 | 0 | ['Breadth-First Search', 'C++'] | 0 |
nearest-exit-from-entrance-in-maze | SOLVED-JAVA BFS | solved-java-bfs-by-yaoyuanzhang06-db0w | \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 | yaoyuanzhang06 | NORMAL | 2021-07-10T16:05:34.532881+00:00 | 2022-03-04T20:10:54.761186+00:00 | 735 | false | ```\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``` | 3 | 0 | ['Breadth-First Search', 'Java'] | 9 |
nearest-exit-from-entrance-in-maze | Simple C++ || BFS || Straight-Forward Solution || | simple-c-bfs-straight-forward-solution-b-72fo | \nclass Solution {\npublic:\n int dir[5]={0,1,0,-1,0};\n int nearestExit(vector<vector<char>>& maze, vector<int>& e) {\n vector<vector<bool>>vi | satvikshrivas | NORMAL | 2021-07-10T16:05:06.583263+00:00 | 2021-07-11T17:50:14.839366+00:00 | 454 | false | ```\nclass Solution {\npublic:\n int dir[5]={0,1,0,-1,0};\n int nearestExit(vector<vector<char>>& maze, vector<int>& e) {\n vector<vector<bool>>vis(maze.size(),vector<bool>(maze[0].size(),0));\n queue<vector<int>>q;\n q.push({e[0],e[1],0});\n vis[e[0]][e[1]]=1;\n while(!q.empty()){\n vector<int>p=q.front();q.pop();\n for(int i =0;i<4;i++){\n int x=p[0]+dir[i],y=p[1]+dir[i+1];\n\n if(x<0 || y<0 || x>=maze.size() || y>=maze[0].size() || maze[x][y]==\'+\')continue;\n if((x==0 || y==0 || x==(maze.size()-1) || y==(maze[0].size()-1)) && maze[x][y]!=\'+\' && !vis[x][y])return p[2]+1;\n\t\t\t\t\t// To avoid TLE mark the cell {x,y} as Visited\n if( maze[x][y]!=\'+\' && !vis[x][y])vis[x][y]=1,q.push({x,y,p[2]+1});\n }\n \n }\n return -1;\n }\n};\n\n``` | 3 | 0 | ['Breadth-First Search', 'C'] | 2 |
nearest-exit-from-entrance-in-maze | Java BFS | java-bfs-by-vikrant_pc-qkgl | \npublic int nearestExit(char[][] maze, int[] entrance) {\n\tint[][] directions = new int[][] {{0,1}, {1,0}, {0,-1},{-1,0}};\n\tQueue<Integer> queue = new Linke | vikrant_pc | NORMAL | 2021-07-10T16:00:42.014912+00:00 | 2021-07-10T16:08:14.433823+00:00 | 331 | false | ```\npublic int nearestExit(char[][] maze, int[] entrance) {\n\tint[][] directions = new int[][] {{0,1}, {1,0}, {0,-1},{-1,0}};\n\tQueue<Integer> queue = new LinkedList<>();\n\tqueue.offer(entrance[0]); queue.offer(entrance[1]);\n\tfor(int currentDistance = 0; !queue.isEmpty(); currentDistance++) {\n\t\tint n = queue.size()/2;\n\t\tfor(int k=0;k<n;k++) {\n\t\t\tint i = queue.poll(), j = queue.poll();\n\t\t\tfor(int[] dir: directions) \n\t\t\t\tif(i+dir[0]>=0 && i+dir[0]<maze.length && j+dir[1]>=0 && j+dir[1]<maze[0].length) {\n\t\t\t\t\tif(maze[i+dir[0]][j+dir[1]]==\'.\') {\n\t\t\t\t\t\tmaze[i+dir[0]][j+dir[1]] = \'+\';\n\t\t\t\t\t\tqueue.offer(i+dir[0]); queue.offer(j+dir[1]); \n\t\t\t\t\t}\n\t\t\t\t} else if (i != entrance[0] || j != entrance[1]) return currentDistance;\n\t\t}\n\t}\n\treturn -1;\n}\n``` | 3 | 2 | [] | 0 |
nearest-exit-from-entrance-in-maze | ✅✅ Classical BFS || Beginner Friendly || Easy Solution | classical-bfs-beginner-friendly-easy-sol-6208 | IntuitionWe need to find the shortest path from the entrance to any exit in the maze.
Since we are looking for the shortest path in an unweighted grid, BFS is t | Karan_Aggarwal | NORMAL | 2025-03-19T17:50:38.970916+00:00 | 2025-03-19T17:50:38.970916+00:00 | 252 | false | # Intuition
We need to find the shortest path from the entrance to any exit in the maze.
Since we are looking for the shortest path in an unweighted grid, **BFS** is the optimal approach.
# Approach
1. **Initialize BFS**:
- Push the `entrance` into a queue and mark it as visited (`'+'`).
- Use a `directions` array to explore up, down, left, and right.
2. **BFS Traversal**:
- At each level, process all nodes in the queue.
- If a node (not the entrance) is on the boundary, return the current step count.
- Otherwise, explore its unvisited neighbors and mark them as visited.
3. **If No Exit is Found**:
- Return `-1`.
# Time Complexity
- **O(M * N)** in the worst case when all cells are visited.
# Space Complexity
- **O(M * N)** for the queue in the worst case.
# Code
```cpp []
class Solution {
public:
vector<vector<int>>directions={{0,1},{0,-1},{1,0},{-1,0}};
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
int m=maze.size(),n=maze[0].size();
int ans=0;
queue<pair<int,int>>q;
q.push({entrance[0],entrance[1]});
maze[entrance[0]][entrance[1]]='+';
auto hasReached=[&](int i,int j){
return (i==0 || j==0 || i==m-1 || j==n-1);
};
while(!q.empty()){
int N=q.size();
while(N--){
auto currNode=q.front();
q.pop();
if(currNode!=make_pair(entrance[0],entrance[1]) &&
hasReached(currNode.first,currNode.second)){
return ans;
}
for(auto &dir:directions){
int i_=currNode.first+dir[0];
int j_=currNode.second+dir[1];
if(i_>=0 && i_<m && j_>=0 && j_<n && maze[i_][j_]!='+'){
q.push({i_,j_});
maze[i_][j_]='+';
}
}
}
ans++;
}
return -1;
}
};
```
# Have a Good Day 😊 UpVote? | 2 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'C++'] | 0 |
nearest-exit-from-entrance-in-maze | ✅Beats 100% | ✅BFS Solution | C++ | beats-100-bfs-solution-c-by-sajal0701-7wcg | 🚀 Nearest Exit in a Maze🧠 IntuitionThe problem asks us to find the shortest path from a given entrance to any exit in the maze. Since we're looking for the shor | Sajal0701 | NORMAL | 2025-02-03T18:40:51.725161+00:00 | 2025-02-03T18:40:51.725161+00:00 | 323 | false | # 🚀 Nearest Exit in a Maze
## 🧠 Intuition
The problem asks us to find the shortest path from a given entrance to any exit in the maze. Since we're looking for the shortest path, we can apply **Breadth-First Search (BFS)**.
- **BFS** ensures that we explore all possible paths level by level, and the first exit we encounter will be the nearest one.
- We track the visited cells to avoid revisiting them, which would otherwise result in unnecessary computations.
- The key observation is that any exit lies on the boundary of the maze, and we can return the first such boundary cell we encounter during BFS.
## 🛠️ Approach
1. **Initialization**:
- Start by marking the entrance as visited.
- Use a queue to explore the maze, starting from the entrance.
- Maintain a set of directions (up, down, left, right) for BFS traversal.
2. **BFS Traversal**:
- Explore the maze using BFS.
- For each cell, if it is an exit (a boundary cell), return the distance from the entrance.
- Mark each cell as visited before adding it to the queue to avoid cycles.
3. **Exit Conditions**:
- If a boundary cell is reached, and it is not the entrance, return the distance.
- If no exit is found, return `-1`.
## ⏳ Complexity
- **Time Complexity**: **O(m × n)**
- Each cell is visited at most once, so BFS runs in linear time with respect to the number of cells in the maze.
- **Space Complexity**: **O(m × n)**
- The space complexity is dominated by the queue and the visited array, both of which store the state of each cell.
## 💻 Code
```cpp
class Solution {
public:
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
int m = maze.size();
int n = maze[0].size();
vector<vector<int>> vis(m, vector<int>(n, 0));
vis[entrance[0]][entrance[1]] = 1;
queue<pair<int, int>> q;
q.push({entrance[0], entrance[1]});
vector<pair<int, int>> dir = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int ans = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
auto top = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
int r = top.first + dir[k].first;
int c = top.second + dir[k].second;
if (r < 0 || c < 0 || r >= m || c >= n || vis[r][c] ||
maze[r][c] == '+')
continue;
else if (r == 0 || c == 0 || r == m - 1 || c == n - 1)
return ans + 1;
q.push({r, c});
vis[r][c] = 1;
}
}
ans++;
}
return -1;
}
};
| 2 | 0 | ['C++'] | 0 |
nearest-exit-from-entrance-in-maze | Python 💯| Simple BFS | 😊 | python-simple-bfs-by-ashishgupta291-yq65 | Intuitionwe have to find shortest path from entrance to nearest cell at border with ".", we can use Dijkstra algo. since cost is same for all the movements simp | ashishgupta291 | NORMAL | 2025-01-30T13:11:34.328330+00:00 | 2025-01-30T13:11:34.328330+00:00 | 296 | false | # Intuition
we have to find shortest path from entrance to nearest cell at border with ".", we can use Dijkstra algo. since cost is same for all the movements simple bfs will also work.
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
Doing BFS traversal untill reaching border of maze, when reached at border return current level.
# Complexity
- Time complexity: O(m*n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(m*n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python []
class Solution(object):
def nearestExit(self, maze, entrance):
directions= [(1, 0), (0, 1), (-1, 0), (0, -1)]
m= len(maze)
n = len(maze[0])
visited = [0]*(m*n)
#bfs
from collections import deque
q = deque()
q.append((tuple(entrance), 0))
visited[entrance[0]*n + entrance[1]]=1
while q:
l, level = q.popleft()
for direc in directions:
x = l[0]+direc[0]
y = l[1]+direc[1]
if 0<=x<m and 0<= y<n:
if maze[x][y]=='.' and not visited[x*n+y]:
visited[x*n+y] = 1
q.append(((x, y), level+1))
if x==0 or x==m-1 or y==n-1 or y ==0:
return level+1
return -1
``` | 2 | 0 | ['Python'] | 0 |
nearest-exit-from-entrance-in-maze | Java Optimal , Simple Approach | java-optimal-simple-approach-by-user8176-ken9 | Nearest Exit from Entrance in MazeProblem DescriptionYou are given an m x n maze (a 2D grid) where:
'.' represents an empty cell,
'#' represents a wall,
The ent | user8176ZR | NORMAL | 2025-01-23T04:29:42.429031+00:00 | 2025-01-23T04:29:42.429031+00:00 | 260 | false | # Nearest Exit from Entrance in Maze
## Problem Description
You are given an `m x n` maze (a 2D grid) where:
- `'.'` represents an empty cell,
- `'#'` represents a wall,
- The entrance is represented by a specific cell in the maze given as an array `entrance` of length 2, i.e., `[entrance[0], entrance[1]]`.
The goal is to find the nearest exit from the entrance. An exit is defined as a cell that is at the border of the maze (first row, last row, first column, or last column). You can only move in four directions: up, down, left, and right.
Write a function `nearestExit(char[][] maze, int[] entrance)` that returns the number of steps to reach the nearest exit. If there is no exit, return `-1`.
## Approach
The problem can be solved using **Breadth-First Search (BFS)** because we are looking for the shortest path to an exit. Here are the steps followed in the code:
1. **Initialization:**
- We store the dimensions of the maze (`r` for rows, `c` for columns).
- We initialize the `minMove` variable to keep track of the minimum number of steps.
- We define the possible movement directions as `up, right, down, left`.
- We initialize a queue and add the entrance to it.
- We mark the entrance as visited by changing its value to `'#'`.
2. **BFS Traversal:**
- Start a BFS where we explore the maze level by level.
- For each level (i.e., each cell in the queue), we check all possible movements.
- If a valid cell (within bounds and not a wall) is found, we check if it's at the border of the maze. If it is, return the current step count as the answer.
- If not, we add the cell to the queue and mark it as visited.
3. **Exit Conditions:**
- If the BFS completes and no exit is found, return `-1`.
## Time Complexity:
- **Time complexity:** $$O(m \times n)$$, where `m` is the number of rows and `n` is the number of columns in the maze. In the worst case, we will visit each cell once.
## Space Complexity:
- **Space complexity:** $$O(m \times n)$$, as we store the queue and the modified maze with the visited cells.
## Code:
```java
class Solution {
public int nearestExit(char[][] maze, int[] entrance) {
int r = maze.length, c = maze[0].length;
int minMove = 0;
int[][] directions = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
Queue<int[]> q = new ArrayDeque<>();
q.offer(entrance);
maze[entrance[0]][entrance[1]] = '#';
while (!q.isEmpty()) {
minMove++;
int qLen = q.size();
for (int i = 0; i < qLen; i++) {
int[] cur = q.poll();
for (int[] dist : directions) {
int row = cur[0] + dist[0];
int col = cur[1] + dist[1];
if (row >= 0 && row < r && col >= 0 && col < c && maze[row][col] == '.') {
if (row == 0 || row == r - 1 || col == 0 || col == c - 1)
return minMove;
q.offer(new int[]{row, col});
maze[row][col] = '#';
}
}
}
}
return -1;
}
}
| 2 | 0 | ['Breadth-First Search', 'Matrix', 'Java'] | 0 |
nearest-exit-from-entrance-in-maze | ✅Easy to understand✅ Beats 100% | easy-to-understand-beats-100-by-mithun00-kmr9 | IntuitionThe problem involves finding the shortest path from the given entrance to the nearest exit in a maze. Each exit lies on the boundary of the maze, and t | Mithun005 | NORMAL | 2025-01-10T05:34:34.667917+00:00 | 2025-01-10T05:34:34.667917+00:00 | 576 | false | # Intuition
The problem involves finding the shortest path from the given entrance to the nearest exit in a maze. Each exit lies on the boundary of the maze, and the path must traverse only empty cells (denoted by '.'). The shortest path can be efficiently computed using Breadth-First Search (BFS), which explores all possible paths layer by layer.
BFS is well-suited for this problem because:
It guarantees finding the shortest path in an unweighted grid.
It systematically explores neighboring cells in all directions before proceeding to cells farther away.
# Approach
Model the Maze as a Grid:
Treat the maze as a 2D grid where each cell is either empty ('.') or blocked ('+').
The goal is to navigate from the entrance to the nearest boundary cell that is not the entrance.
Breadth-First Search (BFS):
Initialize a queue with the entrance coordinates and a step counter (starting at 0).
Use a directions array to explore the four possible moves (up, down, left, right) from each cell.
Mark Cells as Visited:
To avoid revisiting cells, mark each visited cell (including the entrance) as blocked (e.g., by changing '.' to '+').
This ensures that the algorithm doesn't revisit the same cell, reducing unnecessary computations.
Boundary Exit Check:
For every valid neighboring cell, check if it is on the boundary of the grid. If it is, return the number of steps taken to reach this cell.
If no exit is found after exploring all possible paths, return -1.
Efficiency:
The BFS ensures that the shortest path is found with minimal computational overhead.
The grid is updated in place, minimizing additional space usage.
# Complexity
- Time complexity: O(m×n)
- Space complexity: O(min(m,n)),
# Code
```python3 []
class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
q = deque([(entrance[0], entrance[1], 0)])
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
maze[entrance[0]][entrance[1]] = '+' # Mark the entrance as visited
while q:
r, c, steps = q.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
# Check if the next cell is valid and open
if 0 <= nr < len(maze) and 0 <= nc < len(maze[0]) and maze[nr][nc] == '.':
# If it's on the boundary and not the entrance, return steps + 1
if nr == 0 or nr == len(maze) - 1 or nc == 0 or nc == len(maze[0]) - 1:
return steps + 1
# Mark as visited and enqueue
maze[nr][nc] = '+'
q.append((nr, nc, steps + 1))
return -1
``` | 2 | 0 | ['Python3'] | 0 |
nearest-exit-from-entrance-in-maze | BFS | 49ms | 100% Beats | PHP | bfs-49ms-100-beats-php-by-ma7med-r8n5 | Code | Ma7med | NORMAL | 2025-01-09T15:16:31.956999+00:00 | 2025-01-15T08:41:39.151683+00:00 | 484 | false |
# Code
```php []
class Solution {
/**
* @param String[][] $maze
* @param Integer[] $entrance
* @return Integer
*/
function nearestExit($maze, $entrance) {
$rows = count($maze);
$cols = count($maze[0]);
$directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
$queue = new SplQueue();
$queue->enqueue([$entrance[0], $entrance[1], 0]); // [row, col, steps]
$maze[$entrance[0]][$entrance[1]] = '+'; // Mark the entrance as visited
while (!$queue->isEmpty()) {
[$row, $col, $steps] = $queue->dequeue();
foreach ($directions as $direction) {
$newRow = $row + $direction[0];
$newCol = $col + $direction[1];
// Check if the new cell is within bounds and is an empty cell
if ($newRow >= 0 && $newRow < $rows && $newCol >= 0 && $newCol < $cols && $maze[$newRow][$newCol] === '.') {
// Check if the new cell is an exit
if ($newRow == 0 || $newRow == $rows - 1 || $newCol == 0 || $newCol == $cols - 1) {
return $steps + 1;
}
// Mark the cell as visited and add it to the queue
$maze[$newRow][$newCol] = '+';
$queue->enqueue([$newRow, $newCol, $steps + 1]);
}
}
}
return -1; // No exit found
}
}
``` | 2 | 0 | ['PHP'] | 0 |
nearest-exit-from-entrance-in-maze | C++ 0ms 35MB | c-0ms-35mb-by-lng205-lx9p | IntuitionBFS search with performance optimization.Approach
Mark the cell as visited when adding it to the queue is the key. Otherwise all the previous cells in | lng205 | NORMAL | 2024-12-30T13:36:24.324586+00:00 | 2025-02-26T06:47:40.168124+00:00 | 206 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
BFS search with performance optimization.
# Approach
<!-- Describe your approach to solving the problem. -->
- Mark the cell as visited when adding it to the queue is the key. Otherwise all the previous cells in the queue will add the cell again.
# Complexity
for a m x n maze
- Time complexity: $O(mn)$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $O(m+n)$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
The queue can be viewed as a circle of cells and its perimeter is O(m+n).
# Code
```cpp []
class Solution {
public:
struct Cell {
int r, c;
};
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
const int rMax = maze.size() - 1;
const int cMax = maze[0].size() - 1;
int step = 0;
queue<Cell> q;
q.push({entrance[0], entrance[1]});
maze[entrance[0]][entrance[1]] = '+';
while (!q.empty()) {
for (int i = q.size(); i > 0; i--) {
Cell cell = q.front();
q.pop();
int r = cell.r, c = cell.c;
if ((r == 0 || r == rMax || c == 0 || c == cMax) &&
!(r == entrance[0] && c == entrance[1])) return step;
if (r > 0 && maze[r - 1][c] == '.') {
q.push({r - 1, c});
maze[r - 1][c] = '+';
}
if (r < rMax && maze[r + 1][c] == '.') {
q.push({r + 1, c});
maze[r + 1][c] = '+';
}
if (c > 0 && maze[r][c - 1] == '.') {
q.push({r, c - 1});
maze[r][c - 1] = '+';
}
if (c < cMax && maze[r][c + 1] == '.') {
q.push({r, c + 1});
maze[r][c + 1] = '+';
}
}
step++;
}
return -1;
}
};
``` | 2 | 0 | ['C++'] | 0 |
nearest-exit-from-entrance-in-maze | ✅ Simple solution + Why bfs not dfs | simple-solution-why-bfs-not-dfs-by-ibrah-flck | IntuitionMy first intuition was that I need a graph traversal algorithm; maybe DFS or BFS. I used DFS at first, but I hit time limit, when I tried BFS, the solu | IbrahimMohammed47 | NORMAL | 2024-12-26T15:49:13.912689+00:00 | 2024-12-26T15:56:10.345807+00:00 | 167 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
My first intuition was that I need a graph traversal algorithm; maybe DFS or BFS. I used DFS at first, but I hit time limit, when I tried BFS, the solution was accepted.
# But Why BFS Not DFS?
## Why DFS is bad?
DFS will rush deep down a single path until it hits a dead-end or finds a way out, however even this way out might not be the shortest path! and to make sure you find shortest path, you will need to traverse all other paths and compare solutions! which is so bad. Not only that, you will also have to add additional logic to make sure you are not moving in cycles (this is harder than simply checking if a cell is visited or not)
## Why BFS is good?
BFS is very careful. It will guarantee that the first solution it reaches is actually the shortest path because it takes one step forward in all possible solutions and then repeats, until it finds a way out, also it's easy to handle cycles by simply marking cells you visited to not visit them again.
# Approach
A simple queue + while loop can help us with this, handling each cell is made of 4 steps:
- ignore cell if it's invalid or visited already
- mark this cell to not visit it again
- if you reached border, return
- repeat the same on all neighbours.
Notes:
- The queue keeps track of nodes and steps so far, not just the nodes.
- We visit all neighbours without validating them, because we postpone the validation steps when we handle each one separately.. this makes the code simpler.
# Complexity
- Time complexity: O(m x n)
- Space complexity: O(m x n)
# Code
```javascript []
/**
* @param {character[][]} maze
* @param {number[]} entrance
* @return {number}
*/
var nearestExit = function(maze, entrance) {
let queue = []
queue.push([entrance, 0])
const m = maze.length
const n = maze[0].length
while(queue.length){
const [cell, steps] = queue.shift()
const [i,j] = cell
// check if cell is invalid/visited
if(i===m || i===-1 || j===n || j===-1 || maze[i][j]!=='.'){
continue
}
// mark cell as visited
maze[i][j] = '*'
// reached border
if((i===m-1 || i===0 || j===n-1 || j===0) && steps!==0){
return steps
}
// visit neighbours
queue.push([[i,j+1], steps+1])
queue.push([[i,j-1], steps+1])
queue.push([[i+1,j], steps+1])
queue.push([[i-1,j], steps+1])
}
return -1
};
``` | 2 | 0 | ['Breadth-First Search', 'JavaScript'] | 0 |
nearest-exit-from-entrance-in-maze | ✅ Easy Peasy Approach || C++ || Beats 100% 😮😮 | easy-peasy-approach-c-beats-100-by-swaga-xaxv | Intuition\nThe problem requires finding the shortest path to an exit in a maze from a given starting position (entrance). This resembles a shortest path search, | Swagat003 | NORMAL | 2024-10-28T19:48:06.388708+00:00 | 2024-10-29T09:00:53.717620+00:00 | 539 | false | # Intuition\nThe problem requires finding the shortest path to an exit in a maze from a given starting position (entrance). This resembles a **shortest path** search, which is efficiently handled by **Breadth-First Search (BFS)** since BFS explores nodes level by level, ensuring that the first exit found is the closest.\n\n# Approach\n1. **Setup BFS**: We use a queue to hold each cell (or room) to explore, with the row, column, and current distance from the entrance.\n2. **Mark Entrance**: We start from the entrance cell, marking it as visited to prevent revisiting it and avoiding infinite loops.\n3. **Process Each Level in BFS**: For each cell, we:\n - Check if it is an exit. If it is on the boundary of the maze (except the entrance), we return the current distance.\n - Add each unvisited, traversable neighbor (adjacent cells marked \'.\') to the queue and mark it as visited.\n4. **Return Result**: If we exhaust all options without finding an exit, return `-1`.\n\n# Complexity\n- **Time complexity**: \\(O(m \\times n)\\)\n - In the worst case, we visit each cell in the maze once, giving a time complexity of \\(O(m \\times n)\\), where \\(m\\) and \\(n\\) are the maze dimensions.\n\n- **Space complexity**: \\(O(m \\times n)\\)\n - The space complexity also depends on the size of the maze since we use a `visited` matrix of the same size, and the queue could potentially store up to \\(m \\times n\\) cells in the worst case.\n\n# Code\n```cpp\nclass Solution {\npublic:\n struct room {\n int row;\n int col;\n int distance;\n };\n\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int m = maze.size();\n int n = maze[0].size();\n vector<vector<bool>> visited(m,vector<bool>(n,false));\n queue<room> q;\n q.push({entrance[0], entrance[1], 0});\n visited[entrance[0]][entrance[1]] = true;\n\n while (!q.empty()) {\n auto e = q.front();\n int row = e.row;\n int col = e.col;\n int dis = e.distance;\n q.pop();\n\n if ((row == 0 || col == 0 || row == m-1 || col == n-1) && !(row == entrance[0] && col == entrance[1])) {\n return dis;\n }\n\n if ((row - 1 >= 0) && (maze[row - 1][col] == \'.\') && (!visited[row - 1][col])) {\n visited[row - 1][col] = true;\n q.push({row - 1, col, dis + 1});\n }\n if ((col - 1 >= 0) && (maze[row][col - 1] == \'.\') && (!visited[row][col - 1])) {\n visited[row][col - 1] = true;\n q.push({row, col - 1, dis + 1});\n }\n if ((row + 1 < m) && (maze[row + 1][col] == \'.\') && (!visited[row + 1][col])) {\n visited[row + 1][col] = true;\n q.push({row + 1, col, dis + 1});\n }\n if ((col + 1 < n) && (maze[row][col + 1] == \'.\') && (!visited[row][col + 1])) {\n visited[row][col + 1] = true;\n q.push({row, col + 1, dis + 1});\n }\n }\n return -1;\n }\n};\n\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n | 2 | 0 | ['Breadth-First Search', 'Graph', 'C++'] | 1 |
nearest-exit-from-entrance-in-maze | C# BFS Solution | c-bfs-solution-by-getrid-sj7u | Intuition\n Describe your first thoughts on how to solve this problem. To solve the problem of finding the shortest path to the nearest exit in the maze, we can | GetRid | NORMAL | 2024-09-10T20:13:05.735942+00:00 | 2024-09-10T20:13:36.231610+00:00 | 101 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->To solve the problem of finding the shortest path to the nearest exit in the maze, we can approach it as a breadth-first search (BFS) problem. BFS is ideal for exploring all possible paths from the entrance, layer by layer, to ensure that the first exit we reach is the shortest path.\n____\n\n# Approach\n<!-- Describe your approach to solving the problem. -->Initialize the BFS:\n\nUse a queue to track the cells we need to visit, starting from the entrance.\nTrack the number of steps taken to reach each cell.\nMark the entrance as visited to prevent revisiting it.\nBFS Algorithm:\n\nFor each cell in the queue, check its neighboring cells (up, down, left, right).\nIf a neighboring cell is an exit (border cell) and not the entrance, return the number of steps.\nIf a neighboring cell is an empty cell and not visited, add it to the queue and mark it as visited.\nEdge Cases:\n\nIf there are no exits or if all paths are blocked, return -1.\n___\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(m * n), where \'m\' is the number of rows in the maze and \'n\' is the number of columns in the maze.\n____\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(m * n).\n___\n\n# Code\n```csharp []\nusing System.Collections.Generic;\n\npublic class Solution {\n public int NearestExit(char[][] maze, int[] entrance) {\n int m = maze.Length;\n int n = maze[0].Length;\n \n // Directions for moving up, down, left, right\n int[][] directions = new int[][] {\n new int[] {-1, 0}, // Up\n new int[] {1, 0}, // Down\n new int[] {0, -1}, // Left\n new int[] {0, 1} // Right\n };\n \n Queue<(int, int, int)> queue = new Queue<(int, int, int)>();\n queue.Enqueue((entrance[0], entrance[1], 0)); // Add entrance with 0 steps\n maze[entrance[0]][entrance[1]] = \'+\'; // Mark the entrance as visited\n \n // BFS loop\n while (queue.Count > 0) {\n var (x, y, steps) = queue.Dequeue();\n \n foreach (var dir in directions) {\n int newX = x + dir[0];\n int newY = y + dir[1];\n \n // Check if new position is within bounds and is an empty cell\n if (newX >= 0 && newX < m && newY >= 0 && newY < n && maze[newX][newY] == \'.\') {\n // Check if it\'s a border cell (exit)\n if (newX == 0 || newX == m - 1 || newY == 0 || newY == n - 1) {\n return steps + 1;\n }\n \n // Mark as visited and add to the queue\n maze[newX][newY] = \'+\';\n queue.Enqueue((newX, newY, steps + 1));\n }\n }\n }\n \n // If no exit is found\n return -1;\n }\n}\n``` | 2 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'C#'] | 2 |
nearest-exit-from-entrance-in-maze | Python BFS solution- beats 96% in time and 91% in space | python-bfs-solution-beats-96-in-time-and-9wd3 | Intuition\nThis problem can be solved using the Breadth-first search since the minimum number of steps has to be found from a start point. \n\n# Approach\n1. In | aditi2003pai | NORMAL | 2024-07-31T16:28:09.661964+00:00 | 2024-07-31T16:28:09.661998+00:00 | 424 | false | # Intuition\nThis problem can be solved using the Breadth-first search since the minimum number of steps has to be found from a start point. \n\n# Approach\n1. Initialize a queue with in which each entry is a list of 3 elements- [x, y, distance/steps so far].\n2. Append the entrance point with steps 0 to the queue.\n3. In every iteration, pop the leftmost element of queue, find all the points x1,y1 adjacent to the element marked with \'.\'.\n4. If it a border element, return the distance.\n5. Else, append it to the queue with the entry [x1, y1, distance+1].\n\n# Complexity\n- Time complexity:\nO(m*n)\n\n- Space complexity:\nO(m*n)\n\n# Code\n```\nclass Solution(object):\n def nearestExit(self, maze, entrance):\n """\n :type maze: List[List[str]]\n :type entrance: List[int]\n :rtype: int\n """\n m=len(maze)\n n=len(maze[0])\n directions=[(-1,0),(1,0),(0,-1),(0,1)]\n queue=deque()\n queue.append([entrance[0],entrance[1],0])\n maze[entrance[0]][entrance[1]] = \'+\'\n while queue:\n elex,eley,dist=queue.popleft()\n for x,y in directions:\n x1=elex+x\n y1=eley+y\n if 0<=x1<=m-1 and 0<=y1<=n-1 and maze[x1][y1]==\'.\':\n if x1==0 or x1==m-1 or y1==0 or y1==n-1:\n return dist+1\n else:\n maze[x1][y1] = \'+\'\n queue.append([x1,y1,dist+1])\n return -1\n\n\n``` | 2 | 0 | ['Python'] | 0 |
nearest-exit-from-entrance-in-maze | simple BFS || c++ | simple-bfs-c-by-dipanshughime-137i | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dipanshughime | NORMAL | 2024-06-26T13:38:35.573399+00:00 | 2024-06-26T13:38:35.573423+00:00 | 236 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nprivate:\n void bfs(vector<vector<char>>& maze, int& i, int& j, vector<vector<bool>>& visited, int& ans, queue<pair<int, int>>& q) {\n vector<int> row = {-1, 0, 1, 0};\n vector<int> col = {0, 1, 0, -1};\n int n = maze.size();\n int m = maze[0].size();\n int count = 0;\n\n while (!q.empty()) {\n int size = q.size();\n count++;\n for (int i = 0; i < size; i++) {\n pair<int, int> p = q.front(); \n q.pop(); \n int a = p.first;\n int b = p.second;\n\n for (int k = 0; k < 4; k++) {\n int new_row = a + row[k];\n int new_col = b + col[k];\n \n if (new_row >= 0 && new_row < n && new_col >= 0 && new_col < m && !visited[new_row][new_col] && maze[new_row][new_col] == \'.\') {\n if (new_row == 0 || new_row == n - 1 || new_col == 0 || new_col == m - 1) {\n ans = count;\n return;\n }\n visited[new_row][new_col] = true;\n q.push({new_row, new_col});\n }\n }\n }\n }\n }\n\npublic:\n int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {\n int i = entrance[0];\n int j = entrance[1];\n int n = maze.size();\n int m = maze[0].size();\n vector<vector<bool>> visited(n, vector<bool>(m, false));\n visited[i][j] = true;\n\n int ans = -1; // Use -1 to indicate no exit found\n queue<pair<int, int>> q;\n q.push({entrance[0], entrance[1]});\n bfs(maze, i, j, visited, ans, q);\n\n return ans;\n }\n};\n\n``` | 2 | 0 | ['C++'] | 0 |
nearest-exit-from-entrance-in-maze | Beat 80% java solution ✅ || BFS | beat-80-java-solution-bfs-by-apophis29-g5bl | \n\nclass Pair{\n int first;\n int second;\n int step;\n Pair(int fst,int scnd,int step){\n this.first=fst;\n this.second=scnd;\n | Apophis29 | NORMAL | 2024-03-31T04:39:26.434478+00:00 | 2024-03-31T04:39:26.434510+00:00 | 285 | false | ```\n\nclass Pair{\n int first;\n int second;\n int step;\n Pair(int fst,int scnd,int step){\n this.first=fst;\n this.second=scnd;\n this.step=step;\n }\n}\n\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int n=maze.length;\n int m=maze[0].length;\n\n int x=entrance[0];\n int y=entrance[1];\n\n int delRow[]={1,-1,0,0};\n int delCol[]={0,0,1,-1};\n \n int ans=0;\n \n Queue<Pair>q=new LinkedList<Pair>();\n q.add(new Pair(x,y,0));\n \n while(!q.isEmpty()){\n int row=q.peek().first;\n int col=q.peek().second;\n int step=q.peek().step;\n maze[row][col]=\'+\';\n\n \n q.poll();\n\n for(int i=0;i<4;i++){\n int nrow=row+delRow[i];\n int ncol=col+delCol[i];\n\n if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && maze[nrow][ncol]==\'.\'){\n maze[nrow][ncol]=\'+\';\n q.add(new Pair(nrow,ncol,step+1));\n \n \n if(nrow==0 || ncol==0 || nrow==n-1 || ncol==m-1){\n ans=step+1;\n return ans;\n } \n \n }\n\n }\n \n }\n return -1;\n\n\n }\n\n}\n\n```\nThankyou:) | 2 | 0 | [] | 0 |
nearest-exit-from-entrance-in-maze | Easy BFS solution (self explanatory with code comments) - Beats 100% | easy-bfs-solution-self-explanatory-with-k2qmz | Intuition\n Describe your first thoughts on how to solve this problem. \nStarting from the entrance position, perform BFS until we find a boundary cell. Return | vinaygarg25 | NORMAL | 2023-12-11T01:46:50.412145+00:00 | 2023-12-11T01:47:00.811389+00:00 | 442 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStarting from the entrance position, perform BFS until we find a boundary cell. Return -1 if we don\'t \n# Complexity\n- Time complexity: O(m x n) - traversing each cell only once \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m x n) - worst case we will store mxn entries in the queue \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n return bfs(maze, entrance); // bfs is better than dfs because we will be exploring all the possible paths in a single iteration, giving us the minimum path in least amount of exploration. \n\n }\n\n \n private int bfs(char[][] maze, int[] entrance){\n int m = maze.length, n = maze[0].length; \n\n // Directions array {Right, left, down, up}\n int[] rowoffset = {0, 0, 1, -1};\n int[] coloffset = {1, -1, 0, 0};\n\n maze[entrance[0]][entrance[1]] = \'+\'; // marking the entry as visited\n \n \n Queue<Cell> q = new LinkedList<>();\n int steps = 0;\n \n //Adding all the neighbors of entry so we don\'t consider entry as exit\n for(int i=0; i<4; i++){\n int x = entrance[0] + rowoffset[i];\n int y = entrance[1] + coloffset[i];\n if(isWithinBoundary(x, y, m, n) && !isWall(x, y, maze)){\n q.add(new Cell(x, y)); \n maze[x][y] = \'+\';\n }\n }\n // BFS template\n // Add to the root to the queue\n // forEach node in Queue : \n // pop a node\n // find and add valid neighbors to the queue\n // Repeat until queue is not empty\n // Return -1, if we come out of the loop\n \n while(!q.isEmpty()){\n steps++; \n int size = q.size(); \n for( int i=0; i<size; i++){\n Cell cell = q.poll(); \n for(int j=0; j<4; j++){\n int x = cell.x + rowoffset[j];\n int y = cell.y + coloffset[j];\n if(!isWithinBoundary(x, y, m, n)) return steps; \n else {\n if(!isWall(x, y, maze)){\n q.add(new Cell(x, y));\n maze[x][y] = \'+\';\n }\n }\n }\n }\n }\n return -1;\n\n }\n\n private boolean isWithinBoundary(int x, int y, int m, int n){\n if(x < 0 || x>= m) return false;\n if( y< 0 || y >= n) return false; \n return true; \n }\n\n private boolean isWall(int x, int y, char[][] maze){\n return maze[x][y] == \'+\';\n }\n\n // Helper class to easily manage the cell coordinates\n class Cell {\n int x;\n int y;\n\n public Cell(int x_, int y_){\n x = x_;\n y = y_; \n }\n }\n}\n``` | 2 | 0 | ['Breadth-First Search', 'Java'] | 0 |
nearest-exit-from-entrance-in-maze | 💡Swift - Optimal Solution - Breadth-First Search | swift-optimal-solution-breadth-first-sea-vtyx | Solution\n\nclass Solution {\n struct Index: Hashable {\n let x, y: Int\n }\n func nearestExit(_ maze: [[Character]], _ entrance: [Int]) -> Int | bernikovich | NORMAL | 2023-11-24T09:23:30.863541+00:00 | 2023-11-24T09:23:30.863564+00:00 | 45 | false | # Solution\n```\nclass Solution {\n struct Index: Hashable {\n let x, y: Int\n }\n func nearestExit(_ maze: [[Character]], _ entrance: [Int]) -> Int {\n let n = maze.count\n let m = maze[0].count\n\n let startIndex = Index(x: entrance[1], y: entrance[0])\n\n var visited: Set<Index> = [startIndex]\n var queue: Set<Index> = [startIndex]\n\n var steps = 0\n while !queue.isEmpty {\n steps += 1\n \n var nextQueue: Set<Index> = []\n for index in queue {\n for (dX, dY) in [(-1, 0), (0, -1), (1, 0), (0, 1)] {\n let next = Index(x: index.x + dX, y: index.y + dY)\n\n // Validate the index is inside the bounds.\n guard 0..<m ~= next.x && 0..<n ~= next.y else { continue }\n\n // Validate it\'s not a wall. \n guard maze[next.y][next.x] == "." else { continue }\n\n guard visited.insert(next).inserted else { continue }\n nextQueue.insert(next)\n\n // Check if it\'s an exit.\n if (next.x == 0 || next.x == m - 1 || next.y == 0 || next.y == n - 1) {\n return steps\n }\n }\n }\n queue = nextQueue\n }\n\n return -1\n }\n}\n```\n# Complexity\n- Time: $$O(n \\cdot m)$$\n- Space: $$O(max(n, m))$$ | 2 | 0 | ['Breadth-First Search', 'Swift'] | 0 |
minimum-window-substring | Here is a 10-line template that can solve most 'substring' problems | here-is-a-10-line-template-that-can-solv-lct0 | I will first give the solution then show you the magic template.\n\nThe code of solving this problem is below. It might be the shortest among all solutions prov | zjh08177 | NORMAL | 2015-12-02T21:18:34+00:00 | 2018-10-27T01:23:06.183054+00:00 | 906,127 | false | I will first give the solution then show you the magic template.\n\n**The code of solving this problem is below. It might be the shortest among all solutions provided in Discuss**.\n\n string minWindow(string s, string t) {\n vector<int> map(128,0);\n for(auto c: t) map[c]++;\n int counter=t.size(), begin=0, end=0, d=INT_MAX, head=0;\n while(end<s.size()){\n if(map[s[end++]]-->0) counter--; //in t\n while(counter==0){ //valid\n if(end-begin<d) d=end-(head=begin);\n if(map[s[begin++]]++==0) counter++; //make it invalid\n } \n }\n return d==INT_MAX? "":s.substr(head, d);\n }\n\n**Here comes the template.**\n\nFor most substring problem, we are given a string and need to find a substring of it which satisfy some restrictions. A general way is to use a hashmap assisted with two pointers. The template is given below.\n \n\n int findSubstring(string s){\n vector<int> map(128,0);\n int counter; // check whether the substring is valid\n int begin=0, end=0; //two pointers, one point to tail and one head\n int d; //the length of substring\n\n for() { /* initialize the hash map here */ }\n \n while(end<s.size()){\n\n if(map[s[end++]]-- ?){ /* modify counter here */ }\n \n while(/* counter condition */){ \n \n /* update d here if finding minimum*/\n\n //increase begin to make it invalid/valid again\n \n if(map[s[begin++]]++ ?){ /*modify counter here*/ }\n } \n \n /* update d here if finding maximum*/\n }\n return d;\n }\n\n*One thing needs to be mentioned is that when asked to find maximum substring, we should update maximum after the inner while loop to guarantee that the substring is valid. On the other hand, when asked to find minimum substring, we should update minimum inside the inner while loop.*\n\n\nThe code of solving **Longest Substring with At Most Two Distinct Characters** is below:\n\n int lengthOfLongestSubstringTwoDistinct(string s) {\n vector<int> map(128, 0);\n int counter=0, begin=0, end=0, d=0; \n while(end<s.size()){\n if(map[s[end++]]++==0) counter++;\n while(counter>2) if(map[s[begin++]]--==1) counter--;\n d=max(d, end-begin);\n }\n return d;\n }\n\nThe code of solving **Longest Substring Without Repeating Characters** is below:\n\n**Update 01.04.2016, thanks @weiyi3 for advise.**\n\n int lengthOfLongestSubstring(string s) {\n vector<int> map(128,0);\n int counter=0, begin=0, end=0, d=0; \n while(end<s.size()){\n if(map[s[end++]]++>0) counter++; \n while(counter>0) if(map[s[begin++]]-->1) counter--;\n d=max(d, end-begin); //while valid, update d\n }\n return d;\n }\n \nI think this post deserves some upvotes! : ) | 6,827 | 111 | ['String'] | 271 |
minimum-window-substring | Solution | solution-by-deleted_user-0fsy | C++ []\nclass Solution {\npublic:\n string minWindow(string s, string t) {\n vector<int> map(128,0);\n for (char c : t) {\n map[c]++ | deleted_user | NORMAL | 2023-02-09T13:22:28.117867+00:00 | 2023-03-09T09:57:41.400293+00:00 | 57,001 | false | ```C++ []\nclass Solution {\npublic:\n string minWindow(string s, string t) {\n vector<int> map(128,0);\n for (char c : t) {\n map[c]++;\n }\n\n int counter = t.size(), begin = 0, end = 0, d = INT_MAX, head = 0;\n while (end < s.size()){\n if (map[s[end++]]-- > 0) {\n counter--;\n }\n while (counter == 0) {\n if (end - begin < d) {\n head = begin;\n d = end - head;\n }\n if (map[s[begin++]]++ == 0) {\n counter++;\n }\n } \n }\n return d == INT_MAX ? "" : s.substr(head, d);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n if len(s) < len(t):\n return ""\n needstr = collections.defaultdict(int)\n for ch in t:\n needstr[ch] += 1\n needcnt = len(t)\n res = (0, float(\'inf\'))\n start = 0\n for end, ch in enumerate(s):\n if needstr[ch] > 0:\n needcnt -= 1\n needstr[ch] -= 1\n if needcnt == 0:\n while True:\n tmp = s[start]\n if needstr[tmp] == 0:\n break\n needstr[tmp] += 1\n start += 1\n if end - start < res[1] - res[0]:\n res = (start, end)\n needstr[s[start]] += 1\n needcnt += 1\n start += 1\n return \'\' if res[1] > len(s) else s[res[0]:res[1]+1]\n```\n\n```Java []\nclass Solution {\n public String minWindow(String s, String t) {\n if (s == null || t == null || s.length() ==0 || t.length() == 0 ||\n s.length() < t.length()) {\n return new String();\n }\n int[] map = new int[128];\n int count = t.length();\n int start = 0, end = 0, minLen = Integer.MAX_VALUE,startIndex =0;\n for (char c :t.toCharArray()) {\n map[c]++;\n }\n char[] chS = s.toCharArray();\n while (end < chS.length) {\n if (map[chS[end++]]-- >0) {\n count--;\n }\n while (count == 0) {\n if (end - start < minLen) {\n startIndex = start;\n minLen = end - start;\n }\n if (map[chS[start++]]++ == 0) {\n count++;\n }\n }\n }\n\n return minLen == Integer.MAX_VALUE? new String():\n new String(chS,startIndex,minLen);\n }\n}\n```\n | 512 | 3 | ['C++', 'Java', 'Python3'] | 28 |
minimum-window-substring | 12 lines Python | 12-lines-python-by-stefanpochmann-5rwt | The current window is s[i:j] and the result window is s[I:J]. In need[c] I store how many times I need character c (can be negative) and missing tells how many | stefanpochmann | NORMAL | 2015-08-05T09:20:09+00:00 | 2018-10-11T02:38:03.036357+00:00 | 105,664 | false | The current window is `s[i:j]` and the result window is `s[I:J]`. In `need[c]` I store how many times I need character `c` (can be negative) and `missing` tells how many characters are still missing. In the loop, first add the new character to the window. Then, if nothing is missing, remove as much as possible from the window start and then update the result.\n\n def minWindow(self, s, t):\n need, missing = collections.Counter(t), len(t)\n i = I = J = 0\n for j, c in enumerate(s, 1):\n missing -= need[c] > 0\n need[c] -= 1\n if not missing:\n while i < j and need[s[i]] < 0:\n need[s[i]] += 1\n i += 1\n if not J or j - i <= J - I:\n I, J = i, j\n return s[I:J] | 481 | 43 | ['Python'] | 80 |
minimum-window-substring | 🚀🚀🚀 BEATS 100% || EXPLAiNED ✅✅✅ || ANY LANGUAGE ✅✅✅ || 🚀🚀🚀 by PRODONiK | beats-100-explained-any-language-by-prod-7gfe | \n\n# Intuition\nThe goal is to find the minimum window in string s that contains all characters from string t. The intuition is to use a sliding window approac | prodonik | NORMAL | 2024-02-04T00:10:06.073893+00:00 | 2024-02-04T00:27:15.408613+00:00 | 63,657 | false | \n\n# Intuition\nThe goal is to find the minimum window in string `s` that contains all characters from string `t`. The intuition is to use a sliding window approach with two pointers.\n\n# Approach\n- Initialize a character array `map` of size 128 to store the frequency of characters in string `t`.\n- Initialize variables `count`, `start`, `end`, `minLen`, and `startIndex`.\n- Iterate through each character in string `t` and update the character frequency in the `map`.\n- Use two pointers (`start` and `end`) to slide the window and find the minimum window that contains all characters from string `t`.\n - Increment `end` and decrease the frequency in `map` for each character encountered until all characters from `t` are present in the window.\n - When all characters from `t` are present, update `minLen` and `startIndex` based on the current window size and starting index.\n - Increment `start` and increase the frequency in `map` until the window no longer contains all characters from `t`.\n- After the iteration, the minimum window is found, and the result is a substring of `s` starting from `startIndex` with length `minLen`.\n\n# Complexity\n- Time complexity: $$O(n)$$, where n is the length of string `s`.\n- Space complexity: $$O(1)$$, as the `map` array has a constant size (128).\n\n\n\n# UPVOTE iF iT WAS HELPFUL :)\n# Code\n```java []\nclass Solution {\n public String minWindow(String s, String t) {\n if (s == null || t == null || s.length() == 0 || t.length() == 0 ||\n s.length() < t.length()) {\n return new String();\n }\n int[] map = new int[128];\n int count = t.length();\n int start = 0, end = 0, minLen = Integer.MAX_VALUE, startIndex = 0;\n /// UPVOTE !\n for (char c : t.toCharArray()) {\n map[c]++;\n }\n\n char[] chS = s.toCharArray();\n\n while (end < chS.length) {\n if (map[chS[end++]]-- > 0) {\n count--;\n }\n while (count == 0) {\n if (end - start < minLen) {\n startIndex = start;\n minLen = end - start;\n }\n if (map[chS[start++]]++ == 0) {\n count++;\n }\n }\n }\n\n return minLen == Integer.MAX_VALUE ? new String() :\n new String(chS, startIndex, minLen);\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n std::string minWindow(std::string s, std::string t) {\n if (s.empty() || t.empty() || s.length() < t.length()) {\n return "";\n }\n\n std::vector<int> map(128, 0);\n int count = t.length();\n int start = 0, end = 0, minLen = INT_MAX, startIndex = 0;\n /// UPVOTE !\n for (char c : t) {\n map[c]++;\n }\n\n while (end < s.length()) {\n if (map[s[end++]]-- > 0) {\n count--;\n }\n\n while (count == 0) {\n if (end - start < minLen) {\n startIndex = start;\n minLen = end - start;\n }\n\n if (map[s[start++]]++ == 0) {\n count++;\n }\n }\n }\n\n return minLen == INT_MAX ? "" : s.substr(startIndex, minLen);\n }\n};\n```\n```Python []\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n if not s or not t or len(s) < len(t):\n return ""\n\n map = [0] * 128\n count = len(t)\n start = 0\n end = 0\n min_len = float(\'inf\')\n start_index = 0\n # UPVOTE !\n for char in t:\n map[ord(char)] += 1\n\n while end < len(s):\n if map[ord(s[end])] > 0:\n count -= 1\n map[ord(s[end])] -= 1\n end += 1\n\n while count == 0:\n if end - start < min_len:\n start_index = start\n min_len = end - start\n\n if map[ord(s[start])] == 0:\n count += 1\n map[ord(s[start])] += 1\n start += 1\n\n return "" if min_len == float(\'inf\') else s[start_index:start_index + min_len]\n```\n```C# []\npublic class Solution {\n public string MinWindow(string s, string t) {\n if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t) || s.Length < t.Length) {\n return "";\n }\n\n int[] map = new int[128];\n int count = t.Length;\n int start = 0, end = 0, minLen = int.MaxValue, startIndex = 0;\n /// UPVOTE !\n foreach (char c in t) {\n map[c]++;\n }\n\n char[] chS = s.ToCharArray();\n\n while (end < chS.Length) {\n if (map[chS[end++]]-- > 0) {\n count--;\n }\n\n while (count == 0) {\n if (end - start < minLen) {\n startIndex = start;\n minLen = end - start;\n }\n\n if (map[chS[start++]]++ == 0) {\n count++;\n }\n }\n }\n\n return minLen == int.MaxValue ? "" : new string(chS, startIndex, minLen);\n }\n}\n```\n```Go []\nfunc minWindow(s string, t string) string {\n\tif len(s) == 0 || len(t) == 0 || len(s) < len(t) {\n\t\treturn ""\n\t}\n\n\tmapS := make([]int, 128)\n\tcount := len(t)\n\tstart, end := 0, 0\n\tminLen, startIndex := int(^uint(0)>>1), 0\n /// UPVOTE !\n\tfor _, char := range t {\n\t\tmapS[char]++\n\t}\n\n\tfor end < len(s) {\n\t\tif mapS[s[end]] > 0 {\n\t\t\tcount--\n\t\t}\n\t\tmapS[s[end]]--\n\t\tend++\n\n\t\tfor count == 0 {\n\t\t\tif end-start < minLen {\n\t\t\t\tstartIndex = start\n\t\t\t\tminLen = end - start\n\t\t\t}\n\n\t\t\tif mapS[s[start]] == 0 {\n\t\t\t\tcount++\n\t\t\t}\n\t\t\tmapS[s[start]]++\n\t\t\tstart++\n\t\t}\n\t}\n\n\tif minLen == int(^uint(0)>>1) {\n\t\treturn ""\n\t}\n\n\treturn s[startIndex : startIndex+minLen]\n}\n```\n```Ruby []\nclass Solution\n def min_window(s, t)\n return "" if s.empty? || t.empty? || s.length < t.length\n\n map = Array.new(128, 0)\n count = t.length\n start = 0\n end_ = 0\n min_len = Float::INFINITY\n start_index = 0\n # UPVOTE !\n t.each_char { |char| map[char.ord] += 1 }\n\n while end_ < s.length\n if map[s[end_].ord] > 0\n count -= 1\n end\n map[s[end_].ord] -= 1\n end_ += 1\n\n while count == 0\n if end_ - start < min_len\n start_index = start\n min_len = end_ - start\n end\n\n if map[s[start].ord] == 0\n count += 1\n end\n map[s[start].ord] += 1\n start += 1\n end\n end\n\n min_len == Float::INFINITY ? "" : s[start_index, min_len]\n end\nend\n```\n\n | 433 | 2 | ['C++', 'Java', 'Go', 'Python3', 'Ruby', 'C#'] | 18 |
minimum-window-substring | 【Video】Sliding Window solution | video-sliding-window-solution-by-niits-gnec | Intuition\nUse a sliding window to find the smallest range that contains all characters in string t.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/WGNaHa4853Q\ | niits | NORMAL | 2024-09-08T15:28:25.162602+00:00 | 2024-09-08T15:28:25.162635+00:00 | 34,664 | false | # Intuition\nUse a sliding window to find the smallest range that contains all characters in string t.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/WGNaHa4853Q\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 8,404\nThank you for your support!\n\n---\n\n# Approach\n\n1. **Problem Description**: The task is to find the smallest substring in `s` that contains all characters of string `T`.\n\n2. **Approach**:\n - **Using HashMap**: A HashMap is used to keep track of the frequency of each character, allowing efficient management of character counts.\n - **Target Character Management**: Track the frequency of characters in `T` and calculate the minimum window size when all target characters are included in the window.\n - **Window Minimization**: Expand the window to include more characters and contract it to find the smallest valid window.\n\n3. **Algorithm Details**:\n - **Remaining Target Characters**: Track the remaining count of characters from `T`. When all are zero, calculate the window size.\n - **Expanding and Contracting the Window**: Expand the window by adding characters and contract it by removing unnecessary characters.\n - **Updating Minimum Window**: Compute and update the smallest window size as needed.\n\nIf no valid window is found, return an empty string; otherwise, return the smallest valid window.\n\n---\n\nhttps://youtu.be/bU_dXCOWHls\n\n\n# Complexity\n- Time complexity: `O(S + T)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(S + T)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n if len(s) < len(t):\n return ""\n \n char_count = defaultdict(int)\n for ch in t:\n char_count[ch] += 1\n \n target_chars_remaining = len(t)\n min_window = (0, float("inf"))\n start_index = 0\n\n for end_index, ch in enumerate(s):\n if char_count[ch] > 0:\n target_chars_remaining -= 1\n char_count[ch] -= 1\n\n if target_chars_remaining == 0:\n while True:\n char_at_start = s[start_index]\n if char_count[char_at_start] == 0:\n break\n char_count[char_at_start] += 1\n start_index += 1\n \n if end_index - start_index < min_window[1] - min_window[0]:\n min_window = (start_index, end_index)\n \n char_count[s[start_index]] += 1\n target_chars_remaining += 1\n start_index += 1\n \n return "" if min_window[1] > len(s) else s[min_window[0]:min_window[1]+1]\n```\n```javascript []\nvar minWindow = function(s, t) {\n if (s.length < t.length) {\n return "";\n }\n\n const charCount = new Map();\n for (const ch of t) {\n charCount.set(ch, (charCount.get(ch) || 0) + 1);\n }\n\n let targetCharsRemaining = t.length;\n let minWindow = [0, Number.POSITIVE_INFINITY];\n let startIndex = 0;\n\n for (let endIndex = 0; endIndex < s.length; endIndex++) {\n const ch = s[endIndex];\n if (charCount.has(ch) && charCount.get(ch) > 0) {\n targetCharsRemaining--;\n }\n charCount.set(ch, (charCount.get(ch) || 0) - 1);\n\n if (targetCharsRemaining === 0) {\n while (true) {\n const charAtStart = s[startIndex];\n if (charCount.has(charAtStart) && charCount.get(charAtStart) === 0) {\n break;\n }\n charCount.set(charAtStart, (charCount.get(charAtStart) || 0) + 1);\n startIndex++;\n }\n\n if (endIndex - startIndex < minWindow[1] - minWindow[0]) {\n minWindow = [startIndex, endIndex];\n }\n\n charCount.set(s[startIndex], (charCount.get(s[startIndex]) || 0) + 1);\n targetCharsRemaining++;\n startIndex++;\n }\n }\n\n return minWindow[1] >= s.length ? "" : s.slice(minWindow[0], minWindow[1] + 1); \n};\n```\n```java []\nclass Solution {\n public String minWindow(String s, String t) {\n if (s.length() < t.length()) {\n return "";\n }\n\n Map<Character, Integer> charCount = new HashMap<>();\n for (char ch : t.toCharArray()) {\n charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);\n }\n\n int targetCharsRemaining = t.length();\n int[] minWindow = {0, Integer.MAX_VALUE};\n int startIndex = 0;\n\n for (int endIndex = 0; endIndex < s.length(); endIndex++) {\n char ch = s.charAt(endIndex);\n if (charCount.containsKey(ch) && charCount.get(ch) > 0) {\n targetCharsRemaining--;\n }\n charCount.put(ch, charCount.getOrDefault(ch, 0) - 1);\n\n if (targetCharsRemaining == 0) {\n while (true) {\n char charAtStart = s.charAt(startIndex);\n if (charCount.containsKey(charAtStart) && charCount.get(charAtStart) == 0) {\n break;\n }\n charCount.put(charAtStart, charCount.getOrDefault(charAtStart, 0) + 1);\n startIndex++;\n }\n\n if (endIndex - startIndex < minWindow[1] - minWindow[0]) {\n minWindow[0] = startIndex;\n minWindow[1] = endIndex;\n }\n\n charCount.put(s.charAt(startIndex), charCount.getOrDefault(s.charAt(startIndex), 0) + 1);\n targetCharsRemaining++;\n startIndex++;\n }\n }\n\n return minWindow[1] >= s.length() ? "" : s.substring(minWindow[0], minWindow[1] + 1); \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n string minWindow(string s, string t) {\n if (s.length() < t.length()) {\n return "";\n }\n\n unordered_map<char, int> charCount;\n for (char ch : t) {\n charCount[ch]++;\n }\n\n int targetCharsRemaining = t.length();\n int minWindow[2] = {0, INT_MAX};\n int startIndex = 0;\n\n for (int endIndex = 0; endIndex < s.length(); endIndex++) {\n char ch = s[endIndex];\n if (charCount.find(ch) != charCount.end() && charCount[ch] > 0) {\n targetCharsRemaining--;\n }\n charCount[ch]--;\n\n if (targetCharsRemaining == 0) {\n while (true) {\n char charAtStart = s[startIndex];\n if (charCount.find(charAtStart) != charCount.end() && charCount[charAtStart] == 0) {\n break;\n }\n charCount[charAtStart]++;\n startIndex++;\n }\n\n if (endIndex - startIndex < minWindow[1] - minWindow[0]) {\n minWindow[0] = startIndex;\n minWindow[1] = endIndex;\n }\n\n charCount[s[startIndex]]++;\n targetCharsRemaining++;\n startIndex++;\n }\n }\n\n return minWindow[1] >= s.length() ? "" : s.substr(minWindow[0], minWindow[1] - minWindow[0] + 1); \n }\n};\n```\n\n# Step by Step Algorithm\n\n**Step 1: Edge Case Handling**\n\n```python\nif len(s) < len(t):\n return ""\n```\n- If the length of `s` is smaller than the length of `t`, it\'s impossible for `s` to contain `t`. Therefore, return an empty string.\n\n---\n\n**Step 2: Initialize Data Structures**\n\n```python\nchar_count = defaultdict(int)\nfor ch in t:\n char_count[ch] += 1\n```\n- Create a `char_count` dictionary using `defaultdict(int)` to store the frequency of each character in `t`. Initialize all counts to `0` by default.\n- Loop through each character in `t` and increment its count in `char_count`.\n\n---\n\n**Step 3: Initialize Variables**\n\n```python\ntarget_chars_remaining = len(t)\nmin_window = (0, float("inf"))\nstart_index = 0\n```\n- `target_chars_remaining` tracks how many characters from `t` are still needed in the current window. Initially, it\'s set to the length of `t`.\n- `min_window` holds the start and end indices of the smallest window found. Initialize with `(0, float("inf"))`, indicating no valid window found yet.\n- `start_index` is the beginning of the current window in `s`.\n\n---\n\n**Step 4: Expand Window**\n\n```python\nfor end_index, ch in enumerate(s):\n if char_count[ch] > 0:\n target_chars_remaining -= 1\n char_count[ch] -= 1\n```\n- Iterate through `s` using `end_index` as the index and `ch` as the character.\n- If `ch` is a required character (its count in `char_count` is positive), decrement `target_chars_remaining` because one more required character is included.\n- Decrease the count of `ch` in `char_count` because it\'s now part of the window.\n\n---\n\n**Step 5: Contract Window**\n\n```python\nif target_chars_remaining == 0:\n while True:\n char_at_start = s[start_index]\n if char_count[char_at_start] == 0:\n break\n char_count[char_at_start] += 1\n start_index += 1\n```\n- When `target_chars_remaining` is `0`, it means the current window contains all required characters.\n- Start contracting the window from the left by moving `start_index` to the right:\n - Get the character at `start_index`.\n - If its count in `char_count` is `0`, exit the loop because it means this character is needed for a valid window.\n - Otherwise, increment its count and move `start_index` to the right to shrink the window.\n\n---\n\n**Step 6: Update Minimum Window**\n\n```python\nif end_index - start_index < min_window[1] - min_window[0]:\n min_window = (start_index, end_index)\n```\n- After contracting the window, check if the current window is smaller than the previously found minimum window.\n- If so, update `min_window` to the new start and end indices.\n\n---\n\n**Step 7: Adjust for Validity**\n\n```python\nchar_count[s[start_index]] += 1\ntarget_chars_remaining += 1\nstart_index += 1\n```\n- After finding a valid window and updating `min_window`, adjust the character count for the character being removed from the window (`s[start_index]`).\n- Increment `target_chars_remaining` since a required character is no longer in the window.\n- Move `start_index` to the right to continue searching for smaller windows.\n\n---\n\n**Step 8: Return Result**\n\n```python\nreturn "" if min_window[1] > len(s) else s[min_window[0]:min_window[1]+1]\n```\n- After iterating through `s`, check if a valid window was found.\n- If `min_window[1]` is still `float("inf")`, no valid window was found, so return an empty string.\n- Otherwise, return the smallest window substring from `s` using the indices stored in `min_window`.\n\n---\n\nThank you for reading my post. Please upvote it and don\'t forget to subscribe to my channel!\n\n### \u2B50\uFE0F Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n### \u2B50\uFE0F Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### \u2B50\uFE0F Similar Question\n\n#239 - Sliding Window Maximum \n\nhttps://youtu.be/aCdpaTk5qBM\n | 431 | 0 | ['C++', 'Java', 'Python3', 'JavaScript'] | 7 |
minimum-window-substring | Java solution. using two pointers + HashMap | java-solution-using-two-pointers-hashmap-6bvz | public class Solution {\n public String minWindow(String s, String t) {\n if(s == null || s.length() < t.length() || s.length() == 0){\n re | three_thousand_world | NORMAL | 2015-08-11T19:49:32+00:00 | 2018-10-27T04:37:26.563066+00:00 | 92,467 | false | public class Solution {\n public String minWindow(String s, String t) {\n if(s == null || s.length() < t.length() || s.length() == 0){\n return "";\n }\n HashMap<Character,Integer> map = new HashMap<Character,Integer>();\n for(char c : t.toCharArray()){\n if(map.containsKey(c)){\n map.put(c,map.get(c)+1);\n }else{\n map.put(c,1);\n }\n }\n int left = 0;\n int minLeft = 0;\n int minLen = s.length()+1;\n int count = 0;\n for(int right = 0; right < s.length(); right++){\n if(map.containsKey(s.charAt(right))){\n map.put(s.charAt(right),map.get(s.charAt(right))-1);\n if(map.get(s.charAt(right)) >= 0){\n count ++;\n }\n while(count == t.length()){\n if(right-left+1 < minLen){\n minLeft = left;\n minLen = right-left+1;\n }\n if(map.containsKey(s.charAt(left))){\n map.put(s.charAt(left),map.get(s.charAt(left))+1);\n if(map.get(s.charAt(left)) > 0){\n count --;\n }\n }\n left ++ ;\n }\n }\n }\n if(minLen>s.length()) \n { \n return ""; \n } \n \n return s.substring(minLeft,minLeft+minLen);\n }\n} | 273 | 7 | [] | 36 |
minimum-window-substring | Why you failed the last test case: An interesting bug when I used two HashMaps in Java | why-you-failed-the-last-test-case-an-int-qet0 | The logic of my code is just as most other people, to use two HashMap to count t and s. \nI encountered an interesting bug. The code is as following:\n\n\npubli | lajizaijian | NORMAL | 2019-03-31T19:17:03.096144+00:00 | 2019-08-18T01:07:02.546293+00:00 | 7,518 | false | The logic of my code is just as most other people, to use two HashMap to count t and s. \nI encountered an interesting bug. The code is as following:\n```\n\npublic String minWindow(String s, String t) {\n char[] ss = s.toCharArray();\n char[] tt = t.toCharArray();\n Map<Character, Integer> map_s = new HashMap<>();\n Map<Character, Integer> map_t = new HashMap<>();\n int end = 0;\n for (int i = 0; i < tt.length; i++) {\n char c = tt[i];\n map_t.put(c, map_t.getOrDefault(c, 0) + 1);\n if (!map_s.containsKey(c) || map_s.get(c) < map_t.get(c)) { \n while(end < ss.length && ss[end] != c) {\n map_s.put(ss[end], map_s.getOrDefault(ss[end], 0) + 1);\n end++;\n }\n if (end == ss.length) return "";\n map_s.put(c, map_t.get(c));\n end++;\n }\n }\n int min = end;\n int st = 0;\n for (int i = 0; i < end; i++) {\n char c = ss[i];\n if (c == \'m\') {\n if (!map_s.containsKey(c) || !map_t.containsKey(c)) continue;\n if (map_s.get(c) == 423 && map_t.get(c) == 423 && map_s.get(c) != map_t.get(c)) {\n System.out.println("What the hell is going on here?");\n }\n }\n if (map_t.containsKey(c)) {\n if (map_s.get(c) == map_t.get(c)) {\n if (end - i < min) {\n st = i;\n min = end - i;\n }\n while(end < ss.length && ss[end] != c) {\n if (map_t.containsKey(ss[end])) map_s.put(ss[end], map_s.get(ss[end]) + 1);\n end++;\n }\n if (end == ss.length) break;\n end++;\n } else {\n map_s.put(c, map_s.get(c) - 1);\n }\n }\n }\n return s.substring(st, st + min);\n }\n```\n\nIf you copy paste my code, you\'ll see it passes 267/268 but fails at the last test case. And you\'ll see in the last test case, \nthe code will outpu :"What the hell is going on here?".\n\nThe algorithm logic of my code is 100% correct. But something wrong happened in the implementation. As you see, when map_s.get(c) == 423 && map_t.get(c) == 423, actuall map_s.get(c) != map_t.get(c). Interesting and annoying(it took me a few hours to discover this bug T_T), but why?\n\nThe reason is when you put into maps some int value as Integer, the autoboxing process calls the \'valueOf()\' method. The \'valueOf()\' function would return the reference of the object from Integer cache if the value is in the range of -128~127. However, like in the above test case, the two values are 423, then \'valueOf()\' function return two different references when we put 423 into the two maps. In this case, the two Integers, both has value of 423, are two different objects, and they are not == to each other! \n\nSo guys we should really be careful when compare two Integer objects instead of two int!!! | 201 | 0 | [] | 43 |
minimum-window-substring | 16ms simple and neat c++ solution only using a vector. Detailed explanation | 16ms-simple-and-neat-c-solution-only-usi-rqia | Initialize a vector called remaining, which contains the needed\n matching numbers of each character in s. \n 2. If there are still\n characters neede | ztchf | NORMAL | 2015-07-06T20:46:47+00:00 | 2018-08-27T05:37:41.101205+00:00 | 35,686 | false | 1. Initialize a vector called `remaining`, which contains the needed\n matching numbers of each character in `s`. \n 2. If there are still\n characters needed to be contained (increment `i` in this case),\n decrease the matching number of that character and check if it is\n still non-negative. If it is, then it is the character in `t`, so\n decrease the total required number `required`. \n 3. If there is no more\n characters required (increment `start` in this case), record `min`\n and `left` if a smaller length is found. Recover the number of this\n character in the `remaining` and if it is a character in `t`\n increase `required`.\n\n\n----------\n\n class Solution {\n public:\n string minWindow(string s, string t) {\n if (s.size() == 0 || t.size() == 0) return "";\n vector<int> remaining(128, 0);\n int required = t.size();\n for (int i = 0; i < required; i++) remaining[t[i]]++;\n // left is the start index of the min-length substring ever found\n int min = INT_MAX, start = 0, left = 0, i = 0;\n while(i <= s.size() && start < s.size()) {\n if(required) {\n if (i == s.size()) break;\n remaining[s[i]]--;\n if (remaining[s[i]] >= 0) required--;\n i++;\n } else {\n if (i - start < min) {\n min = i -start;\n left = start;\n }\n remaining[s[start]]++;\n if (remaining[s[start]] > 0) required++;\n start++;\n }\n }\n return min == INT_MAX? "" : s.substr(left, min);\n }\n }; | 187 | 4 | [] | 14 |
minimum-window-substring | Python two pointer sliding window with explanation | python-two-pointer-sliding-window-with-e-eq8w | The idea is we use a variable-length sliding window which is gradually applied across the string. We use two pointers: start and end to mark the sliding window. | rarara | NORMAL | 2019-01-27T08:27:41.300218+00:00 | 2023-12-11T20:59:17.414998+00:00 | 23,574 | false | The idea is we use a variable-length sliding window which is gradually applied across the string. We use two pointers: start and end to mark the sliding window. We start by fixing the start pointer and moving the end pointer to the right. The way we determine the current window is a valid one is by checking if all the target letters have been found in the current window. If we are in a valid sliding window, we first make note of the sliding window of the most minimum length we have seen so far. Next we try to contract the sliding window by moving the start pointer. If the sliding window continues to be valid, we note the new minimum sliding window. If it becomes invalid (all letters of the target have been bypassed), we break out of the inner loop and go back to moving the end pointer to the right.\n\n```python\nclass Solution(object):\n def minWindow(self, search_string, target):\n """\n :type s: str\n :type t: str\n :rtype: str\n """\n target_letter_counts = collections.Counter(target)\n start = 0\n end = 0\n min_window = ""\n target_len = len(target) \n \n for end in range(len(search_string)):\n\t\t\t# If we see a target letter, decrease the total target letter count\n\t\t\tif target_letter_counts[search_string[end]] > 0:\n target_len -= 1\n\n # Decrease the letter count for the current letter\n\t\t\t# If the letter is not a target letter, the count just becomes -ve\n\t\t\ttarget_letter_counts[search_string[end]] -= 1\n \n\t\t\t# If all letters in the target are found:\n while target_len == 0:\n window_len = end - start + 1\n if not min_window or window_len < len(min_window):\n\t\t\t\t\t# Note the new minimum window\n min_window = search_string[start : end + 1]\n \n\t\t\t\t# Increase the letter count of the current letter\n target_letter_counts[search_string[start]] += 1\n \n\t\t\t\t# If all target letters have been seen and now, a target letter is seen with count > 0\n\t\t\t\t# Increase the target length to be found. This will break out of the loop\n if target_letter_counts[search_string[start]] > 0:\n target_len += 1\n \n start+=1\n \n return min_window\n``` | 178 | 1 | [] | 27 |
minimum-window-substring | Sharing my straightforward O(n) solution with explanation | sharing-my-straightforward-on-solution-w-0d5s | string minWindow(string S, string T) {\n string result;\n if(S.empty() || T.empty()){\n return result;\n }\n unordered_ma | zxyperfect | NORMAL | 2014-12-14T21:10:59+00:00 | 2014-12-14T21:10:59+00:00 | 56,791 | false | string minWindow(string S, string T) {\n string result;\n if(S.empty() || T.empty()){\n return result;\n }\n unordered_map<char, int> map;\n unordered_map<char, int> window;\n for(int i = 0; i < T.length(); i++){\n map[T[i]]++;\n }\n int minLength = INT_MAX;\n int letterCounter = 0;\n for(int slow = 0, fast = 0; fast < S.length(); fast++){\n char c = S[fast];\n if(map.find(c) != map.end()){\n window[c]++;\n if(window[c] <= map[c]){\n letterCounter++;\n }\n }\n if(letterCounter >= T.length()){\n while(map.find(S[slow]) == map.end() || window[S[slow]] > map[S[slow]]){\n window[S[slow]]--;\n slow++;\n }\n if(fast - slow + 1 < minLength){\n minLength = fast - slow + 1;\n result = S.substr(slow, minLength);\n }\n }\n }\n return result;\n }\n\nThere are three key variables in my solution: \n\n unordered_map <char, int> map; unordered_map<char, int> window; int letterCounter;\n\nvariable "map" is used to indicate what characters and how many characters are in T.\n\nvariable "window" is to indicate what characters and how many characters are between pointer "slow" and pointer "fast".\n\nNow let's start.\n\nThe first For loop is used to construct variable "map".\n\nThe second For loop is used to find the minimum window.\n\nThe first thing we should do in the second For loop is to find a window which can cover T. I use "letterCounter" to be a monitor. If "letterCounter" is equal to T.length(), then we find this window. Before that, only the first If clause can be executed. However, after we find this window, the second If clause can also be executed. \n\nIn the second If clause, we move "slow" forward in order to shrink the window size. Every time finding a smaller window, I update the result. \n\nAt the end of program, I return result, which is the minimum window. | 139 | 4 | ['Hash Table', 'Two Pointers', 'C++'] | 19 |
minimum-window-substring | Simple Python sliding window solution with detailed explanation | simple-python-sliding-window-solution-wi-lp98 | \nfrom collections import Counter\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n \'\'\'\n Keep t_counter of char counts in | gins1 | NORMAL | 2020-12-11T20:17:49.666774+00:00 | 2020-12-11T20:20:31.731418+00:00 | 21,066 | false | ```\nfrom collections import Counter\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n \'\'\'\n Keep t_counter of char counts in t\n \n We make a sliding window across s, tracking the char counts in s_counter\n We keep track of matches, the number of chars with matching counts in s_counter and t_counter\n Increment or decrement matches based on how the sliding window changes\n When matches == len(t_counter.keys()), we have a valid window. Update the answer accordingly\n \n How we slide the window:\n Extend when matches < chars, because we can only get a valid window by adding more.\n Contract when matches == chars, because we could possibly do better than the current window.\n \n How we update matches:\n This only applies if t_counter[x] > 0.\n If s_counter[x] is increased to match t_counter[x], matches += 1\n If s_counter[x] is increased to be more than t_counter[x], do nothing\n If s_counter[x] is decreased to be t_counter[x] - 1, matches -= 1\n If s_counter[x] is decreased to be less than t_counter[x] - 1, do nothing\n \n Analysis:\n O(s + t) time: O(t) to build t_counter, then O(s) to move our sliding window across s. Each index is only visited twice.\n O(s + t) space: O(t) space for t_counter and O(s) space for s_counter\n \'\'\'\n \n if not s or not t or len(s) < len(t):\n return \'\'\n \n t_counter = Counter(t)\n chars = len(t_counter.keys())\n \n s_counter = Counter()\n matches = 0\n \n answer = \'\'\n \n i = 0\n j = -1 # make j = -1 to start, so we can move it forward and put s[0] in s_counter in the extend phase \n \n while i < len(s):\n \n # extend\n if matches < chars:\n \n # since we don\'t have enough matches and j is at the end of the string, we have no way to increase matches\n if j == len(s) - 1:\n return answer\n \n j += 1\n s_counter[s[j]] += 1\n if t_counter[s[j]] > 0 and s_counter[s[j]] == t_counter[s[j]]:\n matches += 1\n\n # contract\n else:\n s_counter[s[i]] -= 1\n if t_counter[s[i]] > 0 and s_counter[s[i]] == t_counter[s[i]] - 1:\n matches -= 1\n i += 1\n \n # update answer\n if matches == chars:\n if not answer:\n answer = s[i:j+1]\n elif (j - i + 1) < len(answer):\n answer = s[i:j+1]\n \n return answer\n``` | 134 | 1 | ['Sliding Window', 'Python', 'Python3'] | 10 |
minimum-window-substring | Accepted O(n) solution | accepted-on-solution-by-heleifz-j255 | class Solution {\n public:\n string minWindow(string S, string T) {\n if (S.empty() || T.empty())\n {\n return "" | heleifz | NORMAL | 2014-09-03T17:23:59+00:00 | 2018-09-22T02:42:58.968651+00:00 | 89,338 | false | class Solution {\n public:\n string minWindow(string S, string T) {\n if (S.empty() || T.empty())\n {\n return "";\n }\n int count = T.size();\n int require[128] = {0};\n bool chSet[128] = {false};\n for (int i = 0; i < count; ++i)\n {\n require[T[i]]++;\n chSet[T[i]] = true;\n }\n int i = -1;\n int j = 0;\n int minLen = INT_MAX;\n int minIdx = 0;\n while (i < (int)S.size() && j < (int)S.size())\n {\n if (count)\n {\n i++;\n require[S[i]]--;\n if (chSet[S[i]] && require[S[i]] >= 0)\n {\n count--;\n }\n }\n else\n {\n if (minLen > i - j + 1)\n {\n minLen = i - j + 1;\n minIdx = j;\n }\n require[S[j]]++;\n if (chSet[S[j]] && require[S[j]] > 0)\n {\n count++;\n }\n j++;\n }\n }\n if (minLen == INT_MAX)\n {\n return "";\n }\n return S.substr(minIdx, minLen);\n }\n };\n\nImplementation of [mike3's idea][1]\n\nrunning time : 56ms.\n\n\n [1]: https://oj.leetcode.com/discuss/5469/is-the-length-of-t-considered-constant-or-m | 116 | 4 | [] | 27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.