Skip to content

Commit 9c9ed6e

Browse files
committed
Update spiral_matrix.py
1 parent f87bd4c commit 9c9ed6e

File tree

1 file changed

+17
-29
lines changed

1 file changed

+17
-29
lines changed

spiral-matrix/spiral_matrix.py

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def spiral_matrix(size: int) -> list:
2727
1 and increasing as the spiral proceeds clockwise inward.
2828
"""
2929
# Set initial data
30-
result: list = _create_zero_matrix(size)
30+
result: list = [[0] * size for i in range(size)]
3131
num: int = 1
3232
max_num: int = size * size
3333
direction: str = "right"
@@ -58,35 +58,23 @@ def _set_direction(direction: str, result: list, x_y: list, size: int) -> str:
5858
row, col = x_y
5959
if direction == "right":
6060
if col + 1 < size and result[row][col + 1] == 0:
61-
return "right"
62-
return "down"
63-
64-
if direction == "down":
61+
direction = "right"
62+
else:
63+
direction = "down"
64+
elif direction == "down":
6565
if row + 1 < size and result[row + 1][col] == 0:
66-
return "down"
67-
return "left"
68-
69-
if direction == "up":
66+
direction = "down"
67+
else:
68+
direction = "left"
69+
elif direction == "up":
7070
if row - 1 >= 0 and result[row - 1][col] == 0:
71-
return "up"
72-
return "right"
73-
74-
if direction == "left":
71+
direction = "up"
72+
else:
73+
direction = "right"
74+
elif direction == "left":
7575
if col - 1 >= 0 and result[row][col - 1] == 0:
76-
return "left"
77-
return "up"
78-
79-
80-
def _create_zero_matrix(size: int) -> list:
81-
"""
82-
Create a square matrix of zeros.
83-
84-
:param size: The dimension of the matrix to create.
85-
:return: A two-dimensional list of shape ``size x size`` filled with zeros.
86-
"""
87-
result: list = []
76+
direction = "left"
77+
else:
78+
direction = "up"
8879

89-
for row in range(size):
90-
result.append([0] * size)
91-
92-
return result
80+
return direction

0 commit comments

Comments
 (0)