Spiral matrix ii

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        matrix = [[0] * n for _ in range(n)]
        loop = n // 2
        mid = n // 2
        startx, starty = 0, 0
        count = 1
        for offset in range(1, loop + 1):
            for i in range(starty, n - offset):
                matrix[startx][i] = count
                count += 1
            for i in range(startx, n - offset):
                matrix[i][n - offset] = count
                count += 1
            for i in range(n - offset, starty, -1):
                matrix[n - offset][i] = count
                count += 1
            for i in range(n - offset, startx, -1):
                matrix[i][starty] = count
                count += 1
            startx += 1
            starty += 1
        if n % 2 != 0:
            matrix[mid][mid] = count

        return matrix

Spiral Matrix II

Difficulty: Medium


Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

 

Example 1:

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

Example 2:

Input: n = 1
Output: [[1]]

 

Constraints:

  • 1 <= n <= 20