meta data for this page
  •  

Set Matrix Zeroes

Leetcode


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:

assets.leetcode.com_uploads_2020_08_17_mat1.jpg

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

Solution 1

Solution 1

public void setZeroes(int[][] matrix) {
  boolean[] rows = new boolean[matrix.length];
  boolean[] cols = new boolean[matrix[0].length];
 
  for (int r = 0; r < matrix.length; r++)
    for (int c = 0; c < matrix[r].length; c++)
      if (matrix[r][c] == 0) {
        rows[r] = true;
        cols[c] = true;
      }
 
  for (int r = 0; r < matrix.length; r++)
    for (int c = 0; c < matrix[r].length; c++)
      if (rows[r] || cols[c]) matrix[r][c] = 0;
}