Skip to content

59. Spiral Matrix II

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

js
/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
  var matrix = []
  for (let i = 0; i < n; i++) {
    matrix[i] = []
  }

  var top = 0
  var bottom = n - 1
  var left = 0
  var right = n - 1
  var num = 1

  while (num <= n * n) {
    for (let i = left; i <= right; i++) {
      matrix[top][i] = num++
    }
    top++

    for (let i = top; i <= bottom; i++) {
      matrix[i][right] = num++
    }
    right--

    for (let i = right; i >= left; i--) {
      matrix[bottom][i] = num++
    }
    bottom--

    for (let i = bottom; i >= top; i--) {
      matrix[i][left] = num++
    }
    left++
  }

  return matrix
}
py
class Solution(object):

    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        matrix = [[0 for i in range(n)] for j in range(n)]
        top, bottom, left, right = 0, n - 1, 0, n - 1
        num = 1

        while num <= n * n:
            for i in range(left, right + 1):
                matrix[top][i] = num
                num += 1
            top += 1

            for i in range(top, bottom + 1):
                matrix[i][right] = num
                num += 1
            right -= 1

            for i in range(right, left - 1, -1):
                matrix[bottom][i] = num
                num += 1
            bottom -= 1

            for i in range(bottom, top - 1, -1):
                matrix[i][left] = num
                num += 1
            left += 1

        return matrix