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