|
| 1 | +- ๋ฌธ์ : https://leetcode.com/problems/set-matrix-zeroes/ |
| 2 | +- ํ์ด: https://algorithm.jonghoonpark.com/2024/02/16/leetcode-73 |
| 3 | + |
| 4 | +## ์ฒ์ ์๊ฐ๋ ๋ฐฉ๋ฒ |
| 5 | + |
| 6 | +```java |
| 7 | +class Solution { |
| 8 | + public void setZeroes(int[][] matrix) { |
| 9 | + List<Index> indexOfZero = new ArrayList<>(); |
| 10 | + |
| 11 | + for (int i = 0; i < matrix.length; i++) { |
| 12 | + for (int j = 0; j < matrix[0].length; j++) { |
| 13 | + if (matrix[i][j] == 0) { |
| 14 | + indexOfZero.add(new Index(i, j)); |
| 15 | + } |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + for (Index index : indexOfZero) { |
| 20 | + // update row |
| 21 | + Arrays.fill(matrix[index.i], 0); |
| 22 | + |
| 23 | + // update column |
| 24 | + for (int i = 0; i < matrix.length; i++) { |
| 25 | + matrix[i][index.j] = 0; |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class Index { |
| 32 | + int i; |
| 33 | + int j; |
| 34 | + |
| 35 | + public Index(int i, int j) { |
| 36 | + this.i = i; |
| 37 | + this.j = j; |
| 38 | + } |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +### TC, SC |
| 43 | + |
| 44 | +๋ฌธ์ ์์ m๊ณผ n์ด ๋ค์๊ณผ ๊ฐ์ด ์ ์๋์ด ์๋ค. |
| 45 | + |
| 46 | +``` |
| 47 | +m == matrix.length |
| 48 | +n == matrix[0].length |
| 49 | +``` |
| 50 | + |
| 51 | +์๊ฐ๋ณต์ก๋๋ `O(n * m)` ๊ณต๊ฐ๋ณต์ก๋๋ `O(n * m)` ์ด๋ค. |
| 52 | + |
| 53 | +## in place ๋ฐฉ์์ผ๋ก ์ ๊ทผํด๋ณด๊ธฐ |
| 54 | + |
| 55 | +๋ฌธ์ ๋ฅผ ์์ธํ ์ฝ์ด๋ณด๋ฉด [in place](https://en.wikipedia.org/wiki/In-place_algorithm) ๋ฐฉ์์ผ๋ก ํ๋ผ๊ณ ๋์ด์๋ค. |
| 56 | + |
| 57 | +```java |
| 58 | +class Solution { |
| 59 | + public void setZeroes(int[][] matrix) { |
| 60 | + int[] row = new int[matrix.length]; |
| 61 | + int[] col = new int[matrix[0].length]; |
| 62 | + |
| 63 | + for (int i = 0; i < matrix.length; i++) { |
| 64 | + for (int j = 0; j < matrix[0].length; j++) { |
| 65 | + if (matrix[i][j] == 0) { |
| 66 | + row[i] = 1; |
| 67 | + col[j] = 1; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + // update row |
| 73 | + for (int i = 0; i < row.length; i++) { |
| 74 | + if (row[i] == 1) { |
| 75 | + Arrays.fill(matrix[i], 0); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + // update column |
| 80 | + for (int j = 0; j < col.length; j++) { |
| 81 | + if (col[j] == 1) { |
| 82 | + for (int i = 0; i < matrix.length; i++) { |
| 83 | + matrix[i][j] = 0; |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | +} |
| 89 | +``` |
| 90 | + |
| 91 | +#### TC, SC |
| 92 | + |
| 93 | +๋ฌธ์ ์์ m๊ณผ n์ด ๋ค์๊ณผ ๊ฐ์ด ์ ์๋์ด ์๋ค. |
| 94 | + |
| 95 | +``` |
| 96 | +m == matrix.length |
| 97 | +n == matrix[0].length |
| 98 | +``` |
| 99 | + |
| 100 | +์๊ฐ๋ณต์ก๋๋ `O(n * m)` ๊ณต๊ฐ๋ณต์ก๋๋ `O(n + m)` ์ด๋ค. ๊ณต๊ฐ ๋ณต์ก๋๊ฐ ๊ฐ์ ๋์๋ค. |
0 commit comments