Leetcode

Leetcode 53

Spiral Matrix

Sailorlqh
2021-09-16
1 min

# 54. Spiral Matrix

Question Link is here.

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        height = len(matrix)
        if(height != 0):
            width = len(matrix[0])
        else:
            return []
        count = 0
        ans = []
        new_count = 0
        while(new_count < height * width):
            for i in range(count, width - count):
                ans.append(matrix[count][i])
                new_count += 1
            for j in range(count + 1, height - count):
                ans.append(matrix[j][width - count - 1])
                new_count += 1
            if(new_count >= height * width):
                break
            for i in range(width - count - 2, count - 1, -1):
                ans.append(matrix[height - count - 1][i])
                new_count += 1
            for j in range(height - 2 - count, count, -1):
                ans.append(matrix[j][count])
                new_count += 1
            count += 1
        return ans
        

This solution has Time Complexity of O(n2)O(n^2).