| 1 | 1 | def spiral_matrix(size: int) -> list[list[int]]: |
| 2 | | pass |
| 2 | # Edge Case: size 0 or negative size |
| 3 | if size <= 0: |
| 4 | return [] |
| 5 | |
| 6 | # Edge Case: size 1 matrix |
| 7 | if size == 1: |
| 8 | return [[1]] |
| 9 | |
| 10 | # Initialize matrix with zeros |
| 11 | matrix = [[0 for _ in range(size)] for _ in range(size)] |
| 12 | |
| 13 | num = 1 |
| 14 | top, bottom = 0, size - 1 |
| 15 | left, right = 0, size - 1 |
| 16 | |
| 17 | while top <= bottom and left <= right: |
| 18 | # Fill top row from left to right |
| 19 | for col in range(left, right + 1): |
| 20 | matrix[top][col] = num |
| 21 | num += 1 |
| 22 | top += 1 |
| 23 | |
| 24 | # Fill right column from top to bottom |
| 25 | for row in range(top, bottom + 1): |
| 26 | matrix[row][right] = num |
| 27 | num += 1 |
| 28 | right -= 1 |
| 29 | |
| 30 | # Fill bottom row from right to left (if there's still a row to fill) |
| 31 | if top <= bottom: |
| 32 | for col in range(right, left - 1, -1): |
| 33 | matrix[bottom][col] = num |
| 34 | num += 1 |
| 35 | bottom -= 1 |
| 36 | |
| 37 | # Fill left column from bottom to top (if there's still a column to fill) |
| 38 | if left <= right: |
| 39 | for row in range(bottom, top - 1, -1): |
| 40 | matrix[row][left] = num |
| 41 | num += 1 |
| 42 | left += 1 |
| 43 | |
| 44 | return matrix |
| 45 | # Handled Edge Cases: size 0 or negative size, size 1 matrix, even vs odd sized matrices, boundary conditions during spiral traversal |