|
1 | 1 | class Solution: |
2 | | - def generateMatrix(self, n: int) -> list[list[int]]: |
3 | | - # Create an n x n matrix filled with zeros |
| 2 | + def generate_matrix(self, n: int) -> list[list[int]]: |
| 3 | + # create an n x n matrix filled with zeros |
4 | 4 | result = [[0] * n for _ in range(n)] |
5 | | - |
| 5 | + |
6 | 6 | # Start filling numbers from 1 to n^2 |
7 | 7 | value = 1 |
8 | | - |
| 8 | + |
9 | 9 | # Define the boundaries for rows and columns |
10 | 10 | rowStart, rowEnd = 0, n - 1 |
11 | 11 | colStart, colEnd = 0, n - 1 |
12 | 12 |
|
13 | 13 | # Continue filling the matrix layer by layer in spiral order |
14 | 14 | while rowStart <= rowEnd and colStart <= colEnd: |
| 15 | + |
15 | 16 | # Step 1: Fill the top row (left → right) |
16 | 17 | for i in range(colStart, colEnd + 1): |
17 | | - result[rowStart][i] = value # assign the current value |
18 | | - value += 1 # move to next number |
| 18 | + result[rowStart][i] = value # assign the current value |
| 19 | + value += 1 # move to next number |
19 | 20 | rowStart += 1 # move top boundary down (row filled) |
20 | | - |
| 21 | + |
21 | 22 | # Step 2: Fill the rightmost column (top → bottom) |
22 | 23 | for j in range(rowStart, rowEnd + 1): |
23 | 24 | result[j][colEnd] = value |
24 | 25 | value += 1 |
25 | 26 | colEnd -= 1 # move right boundary left (column filled) |
26 | | - |
| 27 | + |
27 | 28 | # Step 3: Fill the bottom row (right → left) |
28 | 29 | # Only if there are rows remaining to fill |
29 | 30 | if rowStart <= rowEnd: |
30 | 31 | for k in range(colEnd, colStart - 1, -1): |
31 | 32 | result[rowEnd][k] = value |
32 | 33 | value += 1 |
33 | 34 | rowEnd -= 1 # move bottom boundary up (row filled) |
34 | | - |
| 35 | + |
35 | 36 | # Step 4: Fill the leftmost column (bottom → top) |
36 | 37 | # Only if there are columns remaining to fill |
37 | 38 | if colStart <= colEnd: |
38 | 39 | for l in range(rowEnd, rowStart - 1, -1): |
39 | 40 | result[l][colStart] = value |
40 | 41 | value += 1 |
41 | | - colStart += 1 # move left boundary right (column filled) |
| 42 | + col_start += 1 |
42 | 43 |
|
43 | | - # Return the completed spiral matrix |
| 44 | + # return the completed spiral matrix |
44 | 45 | return result |
45 | 46 |
|
46 | 47 |
|
47 | | -# Example usage: |
| 48 | +# example usage |
48 | 49 | solution = Solution() |
| 50 | +n = 3 # change this to any number, e.g., 4 or 5 |
| 51 | +matrix = solution.generate_matrix(n) |
49 | 52 |
|
50 | | -n = 3 # You can change this to any number, e.g. 4 or 5 |
51 | | -matrix = solution.generateMatrix(n) |
52 | | - |
53 | | -# Print the spiral matrix row by row |
| 53 | +# print the spiral matrix row by row |
54 | 54 | for row in matrix: |
55 | 55 | print(row) |
56 | 56 |
|
57 | 57 |
|
58 | | -# Output: |
59 | | -""" |
| 58 | +# Output: |
| 59 | +''' |
60 | 60 | [1, 2, 3] |
61 | 61 | [8, 9, 4] |
62 | 62 | [7, 6, 5] |
63 | 63 |
|
64 | | -""" |
| 64 | +''' |
0 commit comments