Skip to content

Commit 2f11ec0

Browse files
committed
Solution: Set Matrix Zeros
1 parent 3d57101 commit 2f11ec0

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

set-matrix-zeroes/flynn.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* 풀이
3+
* - matrix 전체를 탐색하다가 값이 0인 좌표를 찾으면
4+
* 그 좌표의 첫번째 열, 첫번째 행 좌표에 표시를 합니다
5+
* if matrix[r][c] == 0
6+
* matrix[r][0] = 0
7+
* matrix[0][c] = 0
8+
* - 만약 해당 좌표가 첫번째 행이거나 첫번째 열이라면 따로 기록해둡니다
9+
* - 첫번째 완전탐색을 마친 후엔 matrix의 첫번째 행, 열을 보고 문제에서 요구하는 바를 수행합니다
10+
*
11+
* Big O
12+
* - M: matrix의 행 개수
13+
* - N: matrix의 열 개수
14+
*
15+
* - Time complexity: O(MN)
16+
* - Space complexity: O(1)
17+
*
18+
*/
19+
20+
class Solution {
21+
public:
22+
void setZeroes(vector<vector<int>>& matrix) {
23+
int m = matrix.size();
24+
int n = matrix[0].size();
25+
26+
bool first_row = false;
27+
bool first_col = false;
28+
29+
for (int r = 0; r < m; ++r) {
30+
for (int c = 0; c < n; ++c) {
31+
if (!matrix[r][c]) {
32+
if (!r) first_row = true;
33+
if (!c) first_col = true;
34+
matrix[r][0] = 0;
35+
matrix[0][c] = 0;
36+
}
37+
}
38+
}
39+
40+
for (int r = 1; r < m; ++r) {
41+
if (!matrix[r][0]) {
42+
for (int c = 1; c < n; ++c) matrix[r][c] = 0;
43+
}
44+
}
45+
46+
for (int c = 1; c < n; ++c) {
47+
if (!matrix[0][c]) {
48+
for (int r = 1; r < m; ++r) matrix[r][c] = 0;
49+
}
50+
}
51+
52+
if (first_row) {
53+
for (int c = 0; c < n; ++c) matrix[0][c] = 0;
54+
}
55+
56+
if (first_col) {
57+
for (int r = 0; r < m; ++r) matrix[r][0] = 0;
58+
}
59+
}
60+
};

0 commit comments

Comments
 (0)