https://leetcode.com/problems/set-matrix-zeroes/description/

 

Set Matrix Zeroes - LeetCode

Can you solve this real interview question? Set Matrix Zeroes - 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 [https://en.wikipedia.org/wiki/In-place_algorithm].   Example 1: [https

leetcode.com

 

주어진 매트릭스에서 0이 존재하는 행과 열을 0으로 전부 변환시키는 문제이다. 별도의 배열을 완성하는게 아니라 기존의 매트릭스를 변환해야한다. 특정 좌표의 (r, c)에 0이 존재하면 해당 r행과 c열을 모두 변환하기에 이를 체크하기 위해 boolean 배열로 체크했다. 아래는 통과코드이다.

  public class Solution {  
  
    public void setZeroes(int[][] matrix) {  
  
        int m = matrix.length;  
        int n = matrix[0].length;  
        boolean[] checkRow = new boolean[m];  
        boolean[] checkCol = new boolean[n];  
  
        for(int i = 0; i < m; i++){  
            for(int j = 0; j < n; j++){  
                if(matrix[i][j] == 0){  
                    checkRow[i] = true;  
                    checkCol[j] = true;  
                }  
            }  
        }  
  
        for(int i = 0; i < m; i++){  
            for(int j = 0; j < n; j++){  
                if(checkRow[i] || checkCol[j]){  
                    matrix[i][j] = 0;  
                }  
            }  
        }  
    }  
  
}

'Algolithm-Leetcode > Math & Geometry' 카테고리의 다른 글

Happy Number  (0) 2026.08.23
Spiral Matrix  (0) 2026.08.14
Rotate Image  (0) 2026.08.07

+ Recent posts