Skip to content

54. Spiral Matrix

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

js
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
  if (!matrix.length) {
    return []
  }

  var top = 0
  var bottom = matrix.length - 1
  var left = 0
  var right = matrix[0].length - 1
  var direction = 0
  var result = []

  while (true) {
    if (direction === 0) {
      for (let i = left; i <= right; i++) {
        result.push(matrix[top][i])
      }
      top++
    } else if (direction === 1) {
      for (let i = top; i <= bottom; i++) {
        result.push(matrix[i][right])
      }
      right--
    } else if (direction === 2) {
      for (let i = right; i >= left; i--) {
        result.push(matrix[bottom][i])
      }
      bottom--
    } else if (direction === 3) {
      for (let i = bottom; i >= top; i--) {
        result.push(matrix[i][left])
      }
      left++
    }

    if (top > bottom || left > right) {
      return result
    }

    direction = (++direction) % 4
  }
}
py
class Solution(object):

    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix:
            return []

        top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
        direction = 0
        result = []

        while True:
            if direction == 0:
                for i in range(left, right + 1):
                    result.append(matrix[top][i])
                top += 1
            elif direction == 1:
                for i in range(top, bottom + 1):
                    result.append(matrix[i][right])
                right -= 1
            elif direction == 2:
                for i in range(right, left - 1, -1):
                    result.append(matrix[bottom][i])
                bottom -= 1
            elif direction == 3:
                for i in range(bottom, top - 1, -1):
                    result.append(matrix[i][left])
                left += 1

            if top > bottom or left > right:
                return result

            direction = (direction + 1) % 4