[Programming]leetcode 54. Spiral Matrix

This is a solution of leetcode 54. Spiral Matrix.

Analysis

This question is not difficult, you just need to take special instances into consideration.

There are four steps in each loop,

  1. print from left to right in the top row
  2. print from up to down in the right col
  3. print from right to left in the bottom row
  4. print from down to up in the left col

Before step 3 and step 4, we need to check if there is still row or col left because the first two steps have cut a row from the top and a col from the right. If you miss this check, you may print duplicated elements.

Now we can write the code.

Code

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return list()
        
        rows, columns = len(matrix), len(matrix[0])
        order = list()
        left, right, top, bottom = 0, columns - 1, 0, rows - 1
        while left <= right and top <= bottom:
            for column in range(left, right + 1):
                order.append(matrix[top][column])
            for row in range(top + 1, bottom + 1):
                order.append(matrix[row][right])
            if left < right and top < bottom:
                for column in range(right - 1, left, -1):
                    order.append(matrix[bottom][column])
                for row in range(bottom, top, -1):
                    order.append(matrix[row][left])
            left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
        return order

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.