Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Create 0054-spiral-matrix-II.py
  • Loading branch information
glowfi authored Jun 7, 2023
commit 0151ea97ca4394ab884b4bafbac33b5e7123ec3b
40 changes: 40 additions & 0 deletions python/0054-spiral-matrix-II.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:

ans=[[0 for _ in range(n)] for _ in range(n)]

top = 0
left = 0
right = len(ans[0])-1
bottom = len(ans)-1

number=1

while left <=right and top <=bottom:
# Left to Right
for i in range(left, right+1):
ans[top][i]=number
number+=1
top += 1

# Top to Bottom
for i in range(top, bottom+1):
ans[i][right]=number
number+=1
right -= 1

# Right to Left
if top <=bottom:
for i in range(right, left - 1, -1):
ans[bottom][i]=number
number+=1
bottom -= 1

# Bottom to Top
if left <=right:
for i in range(bottom, top - 1, -1):
ans[i][left]=number
number+=1
left += 1

return ans