Skip to content

Latest commit

 

History

History
41 lines (35 loc) · 1.15 KB

54.-spiral-matrix.md

File metadata and controls

41 lines (35 loc) · 1.15 KB

54. Spiral Matrix

  • Medium
  • Given an m x n matrix, return all elements of the matrix in spiral order.

Analysis

We go through the matrix following the arrows shown in the graph above.

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res=[]
        if len(matrix)==0:
            return res
        rowl=0
        coll=0
        colr=len(matrix[0])-1
        rowr=len(matrix)-1
        while (rowl<=rowr and coll<=colr):
            for i in range(coll,colr+1):
                res.append(matrix[rowl][i]);
            rowl+=1
            for i in range(rowl,rowr+1):
                res.append(matrix[i][colr]);
            colr-=1
            if (rowl <= rowr):
                for i in range(colr,coll-1,-1):
                    res.append(matrix[rowr][i])
                rowr -= 1
            if (coll <= colr):
                for i in range(rowr,rowl-1,-1):
                    res.append(matrix[i][coll])
                coll += 1
        return res