Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 54 · Matrix

Spiral Matrix

LeetCode 54 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Four shrinking boundaries; guard the bottom and left passes.

मध्यमArrayMatrixSimulation

मी 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.