링크 : https://leetcode.com/problems/set-matrix-zeroes/description/
문제 설명
더보기


Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.
Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Constraints:
- m == matrix.length
- n == matrix[0].length
- 1 <= m, n <= 200
- 231 <= matrix[i][j] <= 231 - 1
Follow up:
- A straightforward solution using O(mn) space is probably a bad idea.
- A simple improvement uses O(m + n) space, but still not the best solution.
- Could you devise a constant space solution?
문제 풀이
첫 번째 반복문
- 각 row를 돌면서 0의 index (j)를 set에 저장, 해당 row에 0이 있다면 zero를 true로 바꿈
- zero가 true라면 해당 라인은 0으로 채워야 하기 때문에 row의 모든 col을 0으로 변환
두 번째 반복문
- 각 row의 0 index를 저장해 두었고 해당 index의 위, 아래도 0으로 변환해야 하기 때문에 matrix를 돌면서 해당 col index가 set에 속해 있다면 0으로 변환
최종적으로 matrix 반환
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
const set = new Set();
for (let i = 0; i < matrix.length; i++) {
let zero = false;
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] === 0) {
set.add(j);
zero = true;
}
}
if (zero) {
for (let j = 0; j < matrix[i].length; j++) {
matrix[i][j] = 0;
}
}
}
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (set.has(j)) {
matrix[i][j] = 0;
}
}
}
return matrix;
};
결론
0으로 변환하는 부분을 2개로 나누어 해결
단순 구현 문제
'코딩테스트 > LeetCode' 카테고리의 다른 글
| LeetCode Search in Rotated Sorted Array (JavaScript) (0) | 2025.12.17 |
|---|---|
| LeetCode Remove Duplicates from Sorted Array ll (JavaScript) (0) | 2025.12.17 |
| LeetCode Simplify Path (JavaScript) (1) | 2025.12.15 |
| LeetCode Minimum Path Sum (JavaScript) (0) | 2025.12.11 |
| LeetCode Unique Paths (JavaScript) (0) | 2025.12.10 |