Spiral Matrix II

LeetCode

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

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

Example 1:

Spiral Matrix II

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

Example 2:

  • Input: n = 1
  • Output: [[1]]
1def generateMatrix(n: int) -> List[List[int]]:
2 matrix = [[0] * n for _ in range(n)]
3 top, bottom = 0, n - 1
4 left, right = 0, n - 1
5 num = 1
6
7 while top <= bottom and left <= right:
8 # Fill Top Row
9 for i in range(left, right + 1):
10 matrix[top][i] = num
11 num += 1
12 top += 1
13
14 # Fill Right Col
15 for i in range(top, bottom + 1):
16 matrix[i][right] = num
17 num += 1
18 right -= 1
19
20 if top <= bottom:
21 # Fill Bottom Row
22 for i in range(right, left - 1, -1):
23 matrix[bottom][i] = num
24 num += 1
25 bottom -= 1
26
27 if left <= right:
28 # Fill Left Col
29 for i in range(bottom, top - 1, -1):
30 matrix[i][left] = num
31 num += 1
32 left += 1
33
34 return matrix
0
0
0
0
0
0
0
0
0
top=0
bottom=2
left=0
right=2
num=1
Step 1 / 6
Step 1:
Initialize n x n matrix with 0s. Boundaries: top=0, bottom=2, left=0, right=2.
Focus: default
top=0bottom=2left=0right=2num=1