11class Solution :
22 def generateMatrix (self , n : int ) -> list [list [int ]]:
3+ # Create an n x n matrix filled with zeros
34 result = [[0 ] * n for _ in range (n )]
5+
6+ # Start filling numbers from 1 to n^2
47 value = 1
58
6- colStart , colEnd = 0 , n - 1
9+ # Define the boundaries for rows and columns
710 rowStart , rowEnd = 0 , n - 1
11+ colStart , colEnd = 0 , n - 1
812
9- while colStart <= colEnd and rowStart <= rowEnd :
10- # Left to Right
13+ # Continue filling the matrix layer by layer in spiral order
14+ while rowStart <= rowEnd and colStart <= colEnd :
15+
16+ # Step 1: Fill the top row (left → right)
1117 for i in range (colStart , colEnd + 1 ):
12- result [rowStart ][i ] = value
13- value += 1
14- rowStart += 1
18+ result [rowStart ][i ] = value # assign the current value
19+ value += 1 # move to next number
20+ rowStart += 1 # move top boundary down (row filled)
1521
16- # Up to Down
22+ # Step 2: Fill the rightmost column (top → bottom)
1723 for j in range (rowStart , rowEnd + 1 ):
1824 result [j ][colEnd ] = value
1925 value += 1
20- colEnd -= 1
26+ colEnd -= 1 # move right boundary left (column filled)
2127
22- # Right to Left
28+ # Step 3: Fill the bottom row (right → left)
29+ # Only if there are rows remaining to fill
2330 if rowStart <= rowEnd :
2431 for k in range (colEnd , colStart - 1 , - 1 ):
2532 result [rowEnd ][k ] = value
2633 value += 1
27- rowEnd -= 1
34+ rowEnd -= 1 # move bottom boundary up (row filled)
2835
29- # Down to Up
36+ # Step 4: Fill the leftmost column (bottom → top)
37+ # Only if there are columns remaining to fill
3038 if colStart <= colEnd :
3139 for l in range (rowEnd , rowStart - 1 , - 1 ):
3240 result [l ][colStart ] = value
3341 value += 1
34- colStart += 1
42+ colStart += 1 # move left boundary right (column filled)
3543
44+ # Return the completed spiral matrix
3645 return result
3746
3847
39- # Test
48+ # Example usage:
4049solution = Solution ()
4150
42- n = 3
43-
51+ n = 3 # You can change this to any number, e.g. 4 or 5
4452matrix = solution .generateMatrix (n )
4553
46- # Print the matrix
54+ # Print the spiral matrix row by row
4755for row in matrix :
4856 print (row )
57+
58+
59+ # Output:
60+ '''
61+ [1, 2, 3]
62+ [8, 9, 4]
63+ [7, 6, 5]
64+
65+ '''
0 commit comments