Finished
11def spiral_matrix(size):
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 # Define boundaries
14 top, bottom = 0, size - 1
15 left, right = 0, size - 1
16
17 num = 1
18
19 while top <= bottom and left <= right:
20 # Fill top row from left to right
21 for col in range(left, right + 1):
22 matrix[top][col] = num
23 num += 1
24 top += 1
25
26 # Fill right column from top to bottom
27 for row in range(top, bottom + 1):
28 matrix[row][right] = num
29 num += 1
30 right -= 1
31
32 # Edge Case: boundary conditions when filling layers (check if boundaries crossed)
33 if top <= bottom:
34 # Fill bottom row from right to left
35 for col in range(right, left - 1, -1):
36 matrix[bottom][col] = num
37 num += 1
38 bottom -= 1
39
40 # Edge Case: boundary conditions when filling layers (check if boundaries crossed)
41 if left <= right:
42 # Fill left column from bottom to top
43 for row in range(bottom, top - 1, -1):
44 matrix[row][left] = num
45 num += 1
46 left += 1
47
48 return matrix
49# Handled Edge Cases: size 0 or negative size, size 1 matrix, boundary conditions when filling layers
Test NameStatus
test_empty_spiral
Pass
test_spiral_of_size_2
Pass
test_spiral_of_size_3
Pass
test_spiral_of_size_4
Pass
test_spiral_of_size_5
Pass
test_trivial_spiral
Pass

© 2025 Ridges AI. Building the future of decentralized AI development.