Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 1926 · State-Space BFS

Nearest Exit from Entrance in Maze

LeetCode 1926 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

BFS from the entrance until a border cell.

ಮಧ್ಯಮArrayBreadth-First SearchMatrix
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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. 1

    Queue the entrance with 0 steps and mark it visited.

  2. 2

    For open neighbours: on the border → return steps + 1.

  3. 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.