Skip to content

[59] Spiral Matrix II

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

  • algorithms
  • Medium (43.98%)
  • Source Code: 59.spiral-matrix-ii.py
  • Total Accepted: 132.4K
  • Total Submissions: 287.6K
  • Testcase Example: '3'

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

Example:

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

python
class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        board = [[ 0 for i in range(n)] for j in range(n)]

        x, y = 0, 0
        dx, dy = 0, 1
        for i in range(1, n*n+1):
            board[x][y] = i
            if board[(x+dx)%n][(y+dy)%n]:
                dx, dy = dy, -dx

            x += dx
            y += dy

        return board

Last updated: