Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 1091 · Shortest Path / BFS-Dijkstra

Shortest Path in Binary Matrix

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

8-direction BFS with path length in dist.

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

ನಾನು Shortest Path in Binary Matrix (LeetCode 1091) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Shortest Path / BFS-Dijkstra ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Moves go in 8 directions with equal cost, so the shortest clear path is a BFS from the top-left corner. Count cells on the path (the start counts as 1).

Approach

  1. 1

    Blocked start → −1.

  2. 2

    dist[0][0] = 1; BFS.

  3. 3

    Relax neighbours with dist + 1.

  4. 4

    Return dist when the target is popped.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

BFS (8 directions)PythonO(n²) time
class Solution:
    def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
        if grid[0][0]==1:
            return -1
        #dijsktra's
        m = len(grid)
        n = len(grid[0])
        dist = [[float("inf")]*n for _ in range(m)]
        q = deque([(0,0)])
        dist[0][0]=1
        while q:
            row,col=q.popleft()
            if row==m-1 and col==n-1:
                return dist[m-1][n-1]
            for di in range(-1,2):
                for dj in range(-1,2):
                    nrow = row+di
                    ncol = col+dj
                    if 0<=nrow<m and 0<=ncol<n and grid[nrow][ncol]==0:
                        if dist[row][col]+1<dist[nrow][ncol]:
                            dist[nrow][ncol]=dist[row][col]+1
                            q.append((nrow,ncol))
        return -1
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Shortest Path in Binary Matrix — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Shortest Path in Binary Matrix ಹಿಂದಿನ intuition ಏನು?

Moves go in 8 directions with equal cost, so the shortest clear path is a BFS from the top-left corner. Count cells on the path (the start counts as 1).

Shortest Path in Binary Matrix (LeetCode 1091) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Blocked start → −1. 2. dist[0][0] = 1; BFS. 3. Relax neighbours with dist + 1. 4. Return dist when the target is popped.

Shortest Path in Binary Matrix ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n²). Space: O(n²). (Accepted approach: BFS (8 directions).)

Shortest Path in Binary Matrix ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

The path length counts cells, not moves.