Leetcode

54. Spiral Matrix

Leeter 2021. 11. 3. 10:16

Description:

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

'''
[1] four-pointer)

idea::
top,bottom,left,right, direction

code::
(below)

-T/C: O(m*n)
-S/C: O(1) # except for output list
'''
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        output=[]
        top,bottom,left,right=0,len(matrix)-1,0,len(matrix[0])-1
        
        dir=0
        
        while top<=bottom and left<=right:
            if dir%4==0:
                for i in range(left,right+1):
                    output.append(matrix[top][i])
                top+=1
            
            if dir%4==1:
                for i in range(top,bottom+1):
                    output.append(matrix[i][right])
                right-=1
            
            if dir%4==2:
                for i in range(right,left-1,-1):
                    output.append(matrix[bottom][i])
                bottom-=1
            
            if dir%4==3:
                for i in range(bottom,top-1,-1):
                    output.append(matrix[i][left])
                left+=1
            dir+=1

        return output