Skip to content

Latest commit

 

History

History
81 lines (60 loc) · 2.97 KB

54.Spiral_Matrix(Medium).md

File metadata and controls

81 lines (60 loc) · 2.97 KB

54. Spiral Matrix (Medium)

Date and Time: Jul 14, 2024, 12:55 (EST)

Link: https://leetcode.com/problems/spiral-matrix/


Question:

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


Example 1:

Input: matrix = [ [1,2,3], [4,5,6], [7,8,9] ]

Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]

Output: [1,2,3,4,8,12,11,10,9,5,6,7]


Constraints:

  • m == matrix.length

  • n == matrix[i].length

  • 1 <= m, n <= 10

  • -100 <= matrix[i][j] <= 100


KeyPoints:

We just repeat four directions moving: left -> right, top -> bottom, right -> left, bottom -> top. So we use four pointers l, r, t, b to indicate these four boundaries. And after each time we finish a traversing, we just shrink the boundary until l == r or t == b, then we can break to return res.


My Solution:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        # l -> r, t -> b, r -> l, b -> t
        l, r = 0, len(matrix[0])
        t, b = 0, len(matrix)
        res = []
        while l < r and t < b:
            # left -> right
            for i in range(l, r):
                res.append(matrix[t][i])
            t += 1  # Top is done
            # top -> bottom
            for i in range(t, b):
                res.append(matrix[i][r-1])
            r -= 1  # Right-most column done
            if l == r or t == b:
                break
            # right -> left
            for i in range(r - 1, l - 1, -1):
                res.append(matrix[b - 1][i])
            b -= 1  # Bottom done
            # bottom -> top
            for i in range(b - 1, t - 1, -1):
                res.append(matrix[i][l])
            l += 1  # left-most column done
        return res

Time Complexity: $O(m * n)$
Space Complexity: $O(m * n)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms