Skip to content

Commit

Permalink
improve: optimize space complexity using matrix markers
Browse files Browse the repository at this point in the history
  • Loading branch information
KwonNayeon committed Jan 25, 2025
1 parent 69b05ea commit d3c182a
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions set-matrix-zeroes/KwonNayeon.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,44 @@ def setZeroes(self, matrix: List[List[int]]) -> None:
for c in zero_cols:
for i in range(len(matrix)):
matrix[i][c] = 0

"""
Time Complexity: O(m*n)
Space Complexity: O(1)
- ์ถ”๊ฐ€์ ์ธ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ฒซ ํ–‰๊ณผ ์—ด์„ ๋งˆ์ปค๋กœ ํ™œ์šฉํ•˜์—ฌ ํ•ด๊ฒฐ
- first_row_zero, first_col_zero ๋‘ ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉ
ํ’€์ด ๋ฐฉ๋ฒ•:
1. ์ฒซ ํ–‰๊ณผ ์ฒซ ์—ด์˜ 0 ์—ฌ๋ถ€๋ฅผ ๋ณ€์ˆ˜์— ์ €์žฅ (๋‚˜์ค‘์— ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•จ)
2. ์ฒซ ํ–‰๊ณผ ์ฒซ ์—ด์„ ๋งˆ์ปค๋กœ ์‚ฌ์šฉ: ํ–‰๋ ฌ์˜ 0 ์œ„์น˜๋ฅผ ์ฒซ ํ–‰/์—ด์— ํ‘œ์‹œ
3. ํ‘œ์‹œ๋œ 0์„ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋จธ์ง€ ํ–‰๋ ฌ์„ ๋ณ€๊ฒฝ (ํ–‰/์—ด ์ „์ฒด๋ฅผ 0์œผ๋กœ ๋ณ€๊ฒฝ)
4. ์ €์žฅํ•ด๋‘” ๋ณ€์ˆ˜๋กœ ์ฒซ ํ–‰/์—ด ์ฒ˜๋ฆฌ (์›๋ž˜ 0์ด์—ˆ๋˜ ํ–‰/์—ด ์ฒ˜๋ฆฌ)
"""
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
# ์ฒซ ํ–‰/์—ด์˜ 0 ์—ฌ๋ถ€ ์ €์žฅ
first_row_zero = any(matrix[0][c] == 0 for c in range(len(matrix[0])))
first_col_zero = any(matrix[r][0] == 0 for r in range(len(matrix)))

# 0์ด ์žˆ๋Š” ์œ„์น˜์˜ ์ฒซ ํ–‰/์—ด์— ํ‘œ์‹œ
for r in range(1, len(matrix)):
for c in range(1, len(matrix[0])):
if matrix[r][c] == 0:
matrix[r][0] = 0 # ์ฒซ ์—ด์— ํ‘œ์‹œ
matrix[0][c] = 0 # ์ฒซ ํ–‰์— ํ‘œ์‹œ

# ํ‘œ์‹œ๋œ 0์„ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋จธ์ง€ ์œ„์น˜ ๋ณ€๊ฒฝ
for r in range(1, len(matrix)):
for c in range(1, len(matrix[0])):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0

# ์ฒซ ํ–‰/์—ด ์ฒ˜๋ฆฌ
if first_row_zero:
for i in range(len(matrix[0])):
matrix[0][i] = 0

if first_col_zero:
for i in range(len(matrix)):
matrix[i][0] = 0

0 comments on commit d3c182a

Please sign in to comment.