Tensorum
YouTubeশেখা শুরু করুন
LeetCode 542 · Multi-Source BFS

01 Matrix

LeetCode 542 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Multi-source BFS from every 0.

মাঝারিArrayDynamic ProgrammingBreadth-First SearchMatrix
LeetCode-এ খুলুন ↗

আমি 01 Matrix (LeetCode 542) এভাবে সমাধান করেছি — Multi-Source BFS প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।

নিচের বিবরণ ইংরেজিতে।

Intuition

Distances grow outward from zeros, so run one BFS from all zeros at once (multi-source). The first time a cell is reached, that's its distance to the nearest zero.

Approach

  1. 1

    Queue every 0 cell with distance 0.

  2. 2

    Pop a cell; for unvisited neighbours set dist = dist + 1 and enqueue.

  3. 3

    Return the distance grid.

আমি কীভাবে সমাধান করেছি

Multi-source BFSPythonO(m·n) time
class Solution:
    def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]:
        visited = set()
        di = [0,+1,0,-1]
        dj = [+1,0,-1,0]
        q = deque([])
        m= len(mat)
        n = len(mat[0])
        dist = [[0]*n for _ in range(m)]
        for row in range(m):
            for col in range(n):
                if mat[row][col]==0:
                    q.append((row,col,0))
                    visited.add((row,col))
        while q:
            row,col,steps = q.popleft()
            for k in range(4):
                nrow = row+di[k]
                ncol = col+dj[k]
                if 0<=nrow<m and 0<=ncol<n and (nrow,ncol) not in visited:
                   dist[nrow][ncol] = 1+dist[row][col]
                   visited.add((nrow,ncol))
                   q.append((nrow,ncol,steps+1))
        return dist
স্টেপ-থ্রু লোড হচ্ছে…

01 Matrix — সাধারণ প্রশ্ন

01 Matrix-এর পেছনে intuition কী?

Distances grow outward from zeros, so run one BFS from all zeros at once (multi-source). The first time a cell is reached, that's its distance to the nearest zero.

01 Matrix (LeetCode 542) কীভাবে সমাধান করবেন?

1. Queue every 0 cell with distance 0. 2. Pop a cell; for unvisited neighbours set dist = dist + 1 and enqueue. 3. Return the distance grid.

01 Matrix-এর time আর space complexity কত?

Time: O(m · n)। Space: O(m · n)। (Accepted approach: Multi-source BFS।)

01 Matrix-এ সাধারণ ভুলগুলো কী?

A BFS per 1-cell would be O((mn)²).