Skip to content

Commit

Permalink
DaleStudy#282 spiral-matrix solution
Browse files Browse the repository at this point in the history
  • Loading branch information
sungjinwi committed Jan 18, 2025
1 parent 16b7109 commit 19e2f54
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions spiral-matrix/sungjinwi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
ํ’€์ด :
์˜ค๋ฅธ์ชฝ, ์•„๋ž˜์ชฝ์œผ๋กœ ์ด๋™ํ•  ๋• ๊ฐ๊ฐ column๊ณผ row๊ฐ€ ์ฆ๊ฐ€ํ•˜๋ฏ€๋กœ direction 1
์™ผ์ชฝ, ์œ„์ชฝ์€ ๊ฐ์†Œํ•˜๋ฏ€๋กœ direction -1
๋กœ ์„ค์ •ํ•˜๊ณ  n_row ๋˜๋Š” n_col๋งŒํผ direction์„ ์ด๋™ํ•˜๋ฉด์„œ ans์— ๋‹ด์•„์ค€๋‹ค
๊ฐ for๋ฌธ์ด ๋๋‚  ๋•Œ๋งˆ๋‹ค n_row ๋˜๋Š” n_col์„ ๊ฐ์†Œ์‹œ์ผœ ์ฃผ๊ณ 
๋‘˜ ์ค‘ ํ•˜๋‚˜๊ฐ€ 0์ด ๋  ๋•Œ๊นŒ์ง€ ๊ณ„์† ์ง„ํ–‰
- col์ด -1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ matrix[0][0]๋ถ€ํ„ฐ appendํ•  ์ˆ˜ ์žˆ๋„๋ก ์œ ์˜
- n_cols, n_rows ๋‘˜ ์ค‘ ํ•˜๋‚˜๋งŒ 0์ด๋˜๋„ ๋๋‚จ์— ์œ ์˜
TC : O(M * N)
matrix ์ „์ฒด๋ฅผ ํ•œ๋ฒˆ์”ฉ ์ˆœํšŒํ•ด์•ผํ•˜๋ฏ€๋กœ
SC : O(1)
returnํ•  ๋ฆฌ์ŠคํŠธ ์™ธ์—๋Š” ์ถ”๊ฐ€์ ์ธ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ์ด ์ƒ์ˆ˜๊ฐœ(5๊ฐœ)์ด๋ฏ€๋กœ
"""

class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
ans = []
n_rows = len(matrix)
n_cols = len(matrix[0])

row = 0
col = -1
direction = 1

while n_cols and n_rows :
for _ in range(n_cols):
col += direction
ans.append(matrix[row][col])
n_rows -= 1

for _ in range(n_rows):
row += direction
ans.append(matrix[row][col])
n_cols -= 1

direction *= -1

return ans

0 comments on commit 19e2f54

Please sign in to comment.