Skip to content

Commit d642590

Browse files
committed
add solution : 73. Set Matrix Zeroes
1 parent 3cd4f15 commit d642590

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

set-matrix-zeroes/mmyeon.ts

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/**
2+
Do not return anything, modify matrix in-place instead.
3+
*/
4+
/**
5+
* @link https://leetcode.com/problems/set-matrix-zeroes/description/
6+
*
7+
* 접근 방법 :
8+
* - 행렬 순회하면서 0이 있는 행과 열을 rowsToZero과 colsToZero에 저장
9+
* - 다시 행렬 순회하면서 rowsToZero과 colsToZero와 포함된 경우 0으로 변경
10+
*
11+
* 시간복잡도 : O(m * n)
12+
* - m * n 행렬 크기만큼 순회
13+
*
14+
* 공간복잡도 : O(m + n)
15+
* - m 행과 n 열 정보 저장
16+
*/
17+
function setZeroes(matrix: number[][]): void {
18+
const rows = matrix.length;
19+
const cols = matrix[0].length;
20+
const rowsToZero = new Set<number>();
21+
const colsToZero = new Set<number>();
22+
for (let row = 0; row < rows; row++) {
23+
for (let col = 0; col < cols; col++) {
24+
if (matrix[row][col] === 0) {
25+
rowsToZero.add(row);
26+
colsToZero.add(col);
27+
}
28+
}
29+
}
30+
31+
for (let row = 0; row < rows; row++) {
32+
for (let col = 0; col < cols; col++) {
33+
if (rowsToZero.has(row) || colsToZero.has(col)) {
34+
matrix[row][col] = 0;
35+
}
36+
}
37+
}
38+
}
39+
40+
// 공간 복잡도 O(m+n)을 O(1)로 개선하기
41+
// set에 행과 열 정보 저장하던 방식을 set없이 첫 번째 행과 열을 활용하는 방법으로 변경
42+
function setZeroes(matrix: number[][]): void {
43+
const rows = matrix.length;
44+
const cols = matrix[0].length;
45+
let hasZeroInFirstRow = false;
46+
let hasZeroInFirstCol = false;
47+
48+
// 첫 번째 열에 0 있는지 여부를 플래그로 저장
49+
for (let row = 0; row < rows; row++) {
50+
if (matrix[row][0] === 0) hasZeroInFirstCol = true;
51+
}
52+
53+
// 첫 번째 행에 0 있는지 여부를 플래그로 저장
54+
for (let col = 0; col < cols; col++) {
55+
if (matrix[0][col] === 0) hasZeroInFirstRow = true;
56+
}
57+
58+
// 첫 번째 행과 열 제외하고 마커 설정하기
59+
for (let row = 1; row < rows; row++) {
60+
for (let col = 1; col < cols; col++) {
61+
if (matrix[row][col] === 0) {
62+
matrix[0][col] = 0;
63+
matrix[row][0] = 0;
64+
}
65+
}
66+
}
67+
68+
// 마커 기반으로 행렬에 반영
69+
for (let row = 1; row < rows; row++) {
70+
for (let col = 1; col < cols; col++) {
71+
if (matrix[row][0] === 0 || matrix[0][col] === 0) matrix[row][col] = 0;
72+
}
73+
}
74+
75+
// 첫 번째 행 업데이트
76+
if (hasZeroInFirstRow) {
77+
for (let col = 0; col < cols; col++) {
78+
matrix[0][col] = 0;
79+
}
80+
}
81+
82+
// 첫 번째 열 업데이트
83+
if (hasZeroInFirstCol) {
84+
for (let row = 0; row < rows; row++) {
85+
matrix[row][0] = 0;
86+
}
87+
}
88+
}

0 commit comments

Comments
 (0)