Tensorum
YouTubeশেখা শুরু করুন
LeetCode 54 · Matrix

Spiral Matrix

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

Four shrinking boundaries; guard the bottom and left passes.

মাঝারিArrayMatrixSimulation
LeetCode-এ খুলুন ↗

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

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

Intuition

Peel the matrix layer by layer with four boundaries. Walk the top row, the right column, the bottom row backwards and the left column upwards, shrinking each boundary after you use it.

Approach

  1. 1

    top, bottom, left, right define the unvisited rectangle.

  2. 2

    Left→right along top, then top++.

  3. 3

    Top→bottom along right, then right−−.

  4. 4

    If rows remain, right→left along bottom; if columns remain, bottom→top along left.

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

Boundary simulationPythonO(m·n) time
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        #4 pointers, top, right, bottom, left
        #move from left to right
        #move from top to bottom
        #move from right to left - handle single row
        #move from bottom to top - handle single col
        m = len(matrix)
        n = len(matrix[0])
        top=0
        bottom = m-1
        left = 0
        right = n-1
        res=[]
        while top<=bottom and left<=right:
            for i in range(left,right+1):
                res.append(matrix[top][i])
            top+=1
            for i in range(top,bottom+1):
                res.append(matrix[i][right])
            right-=1
            if top<=bottom:
                for j in range(right,left-1,-1):
                    res.append(matrix[bottom][j])   
                bottom-=1
            if left<=right:
                for i in range(bottom,top-1,-1):
                    res.append(matrix[i][left]) 
                left+=1
        return res  
স্টেপ-থ্রু লোড হচ্ছে…

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

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

Peel the matrix layer by layer with four boundaries. Walk the top row, the right column, the bottom row backwards and the left column upwards, shrinking each boundary after you use it.

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

1. top, bottom, left, right define the unvisited rectangle. 2. Left→right along top, then top++. 3. Top→bottom along right, then right−−. 4. If rows remain, right→left along bottom; if columns remain, bottom→top along left.

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

Time: O(m·n)। Space: O(1) extra। (Accepted approach: Boundary simulation।)

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

Without the top ≤ bottom and left ≤ right checks, a single remaining row or column is read twice.