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.