ZhangZhihui's Blog  

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

 

My Solution:

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        
        res = []
        i = 0
        j = 0
        direction = 'right'
        right_border = len(matrix[0])
        down_border = len(matrix)
        left_border = -1
        up_border = 0

        for _ in range(len(matrix) * len(matrix[0])):
            res.append(matrix[i][j])

            if direction == 'right':
                if j + 1 == right_border:
                    i += 1
                    direction = 'down'
                    right_border -= 1
                else:
                    j += 1
            elif direction == 'down':
                if i + 1 == down_border:
                    j -= 1
                    direction = 'left'
                    down_border -= 1
                else:
                    i += 1
            elif direction == 'left':
                if j - 1 == left_border:
                    i -= 1
                    direction = 'up'
                    left_border += 1
                else:
                    j -= 1
            elif direction == 'up':
                if i - 1 == up_border:
                    j += 1
                    direction = 'right'
                    up_border += 1
                else:
                    i -= 1

        return res

 

 

posted on 2025-03-16 16:52  ZhangZhihuiAAA  阅读(7)  评论(0)    收藏  举报