[Leetcode] 0059. Spiral Matrix II

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link

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

內容目錄

Python

				
					# time complexity: O(m*n)
# space complexity: O(m*n)
from typing import List


class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        grid = [[0 for _ in range(n)] for _ in range(n)]
        ROW = n
        COL = n
        direction = 1
        row = 0
        col = -1
        i = 1
        while ROW > 0 and COL > 0:
            for _ in range(COL):
                col += direction
                grid[row][col] = i
                i += 1
            ROW -= 1
            for _ in range(ROW):
                row += direction
                grid[row][col] = i
                i += 1
            COL -= 1
            direction *= -1

        return grid


n = 3
print(Solution().generateMatrix(3))
n = 1
print(Solution().generateMatrix(1))
				
			
zh_TW繁體中文