Skip to content

Commit 4fe3771

Browse files
committed
Add spiral_matrix implementation
1 parent 3cea941 commit 4fe3771

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution:
2+
def generateMatrix(self, n: int) -> list[list[int]]:
3+
result = [[0] * n for _ in range(n)]
4+
value = 1
5+
6+
colStart, colEnd = 0, n - 1
7+
rowStart, rowEnd = 0, n - 1
8+
9+
while colStart <= colEnd and rowStart <= rowEnd:
10+
# Left to Right
11+
for i in range(colStart, colEnd + 1):
12+
result[rowStart][i] = value
13+
value += 1
14+
rowStart += 1
15+
16+
# Up to Down
17+
for j in range(rowStart, rowEnd + 1):
18+
result[j][colEnd] = value
19+
value += 1
20+
colEnd -= 1
21+
22+
# Right to Left
23+
if rowStart <= rowEnd:
24+
for k in range(colEnd, colStart - 1, -1):
25+
result[rowEnd][k] = value
26+
value += 1
27+
rowEnd -= 1
28+
29+
# Down to Up
30+
if colStart <= colEnd:
31+
for l in range(rowEnd, rowStart - 1, -1):
32+
result[l][colStart] = value
33+
value += 1
34+
colStart += 1
35+
36+
return result
37+
38+
39+
# Test
40+
solution = Solution()
41+
42+
n = 3
43+
44+
matrix = solution.generateMatrix(n)
45+
46+
# Print the matrix
47+
for row in matrix:
48+
print(row)

0 commit comments

Comments
 (0)