Nearest Exit from Entrance in Maze
LeetCode 1926 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
BFS from the entrance until a border cell.
நான் Nearest Exit from Entrance in Maze (LeetCode 1926) ஐ இப்படித் தீர்த்தேன் — State-Space BFS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Shortest path in an unweighted grid is BFS. Start at the entrance and expand; the first border cell reached (other than the entrance) is the nearest exit.
Approach
- 1
Queue the entrance with 0 steps and mark it visited.
- 2
For open neighbours: on the border → return steps + 1.
- 3
Otherwise mark and enqueue.
நான் எப்படித் தீர்த்தேன்
BFSPythonO(m·n) time
class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
#will start with the entrance, if it reaches border, calculate the steps, do a minimum steps
sr,sc = entrance
q = deque([(sr,sc,0)])
visited = set()
visited.add((sr,sc))
m = len(maze)
n = len(maze[0])
while q:
row,col,steps = q.popleft()
di = [0,+1,0,-1]
dj = [+1,0,-1,0]
for k in range(4):
nrow = row+di[k]
ncol = col+dj[k]
if 0<=nrow<m and 0<=ncol<n and maze[nrow][ncol]=="." and (nrow,ncol) not in visited:
if nrow ==0 or nrow ==m-1 or ncol==0 or ncol==n-1:
return steps+1
visited.add((nrow,ncol))
q.append((nrow,ncol,steps+1))
return -1
Nearest Exit from Entrance in Maze — அடிக்கடி கேட்கப்படும் கேள்விகள்
Nearest Exit from Entrance in Maze பின்னாலுள்ள intuition என்ன?
Shortest path in an unweighted grid is BFS. Start at the entrance and expand; the first border cell reached (other than the entrance) is the nearest exit.
Nearest Exit from Entrance in Maze (LeetCode 1926) ஐ எப்படித் தீர்ப்பது?
1. Queue the entrance with 0 steps and mark it visited. 2. For open neighbours: on the border → return steps + 1. 3. Otherwise mark and enqueue.
Nearest Exit from Entrance in Maze இன் time மற்றும் space complexity என்ன?
Time: O(m · n). Space: O(m · n). (Accepted approach: BFS.)
Nearest Exit from Entrance in Maze இல் பொதுவான தவறுகள் என்ன?
The entrance doesn't count as an exit even if it's on the border.