Skip to content

Commit

Permalink
Solution: Set Matrix Zeros
Browse files Browse the repository at this point in the history
  • Loading branch information
obzva committed Sep 25, 2024
1 parent 3d57101 commit 2f11ec0
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions set-matrix-zeroes/flynn.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* ํ’€์ด
* - matrix ์ „์ฒด๋ฅผ ํƒ์ƒ‰ํ•˜๋‹ค๊ฐ€ ๊ฐ’์ด 0์ธ ์ขŒํ‘œ๋ฅผ ์ฐพ์œผ๋ฉด
* ๊ทธ ์ขŒํ‘œ์˜ ์ฒซ๋ฒˆ์งธ ์—ด, ์ฒซ๋ฒˆ์งธ ํ–‰ ์ขŒํ‘œ์— ํ‘œ์‹œ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค
* if matrix[r][c] == 0
* matrix[r][0] = 0
* matrix[0][c] = 0
* - ๋งŒ์•ฝ ํ•ด๋‹น ์ขŒํ‘œ๊ฐ€ ์ฒซ๋ฒˆ์งธ ํ–‰์ด๊ฑฐ๋‚˜ ์ฒซ๋ฒˆ์งธ ์—ด์ด๋ผ๋ฉด ๋”ฐ๋กœ ๊ธฐ๋กํ•ด๋‘ก๋‹ˆ๋‹ค
* - ์ฒซ๋ฒˆ์งธ ์™„์ „ํƒ์ƒ‰์„ ๋งˆ์นœ ํ›„์—” matrix์˜ ์ฒซ๋ฒˆ์งธ ํ–‰, ์—ด์„ ๋ณด๊ณ  ๋ฌธ์ œ์—์„œ ์š”๊ตฌํ•˜๋Š” ๋ฐ”๋ฅผ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค
*
* Big O
* - M: matrix์˜ ํ–‰ ๊ฐœ์ˆ˜
* - N: matrix์˜ ์—ด ๊ฐœ์ˆ˜
*
* - Time complexity: O(MN)
* - Space complexity: O(1)
*
*/

class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();

bool first_row = false;
bool first_col = false;

for (int r = 0; r < m; ++r) {
for (int c = 0; c < n; ++c) {
if (!matrix[r][c]) {
if (!r) first_row = true;
if (!c) first_col = true;
matrix[r][0] = 0;
matrix[0][c] = 0;
}
}
}

for (int r = 1; r < m; ++r) {
if (!matrix[r][0]) {
for (int c = 1; c < n; ++c) matrix[r][c] = 0;
}
}

for (int c = 1; c < n; ++c) {
if (!matrix[0][c]) {
for (int r = 1; r < m; ++r) matrix[r][c] = 0;
}
}

if (first_row) {
for (int c = 0; c < n; ++c) matrix[0][c] = 0;
}

if (first_col) {
for (int r = 0; r < m; ++r) matrix[r][0] = 0;
}
}
};

0 comments on commit 2f11ec0

Please sign in to comment.