LeetCode – Set Matrix Zeroes (Java)

Given a m * n matrix, if an element is 0, set its entire row and column to 0.
Do it in place.

Analysis

This problem should be solved in place, i.e., no other array should be used. We can use the first column and the first row to track if a row/column should be set to 0.

Since we used the first row and first column to mark the zero row/column, the original values are changed.

Specifically, given, the following matrix
set-matrix-zero-1
this problem can be solved by following 4 steps:

Step 1:
First row contains zero = true;
First column contains zero = false;

Step 2: use first row and column to mark zero row and column.
set-matrix-zero-2

Step 3: set each elements by using marks in first row and column.
set-matrix-zero-3

Step 4: Set first column and row by using marks in step 1.
set-matrix-zero-4

Java Solution

public class Solution {
    public void setZeroes(int[][] matrix) {
        boolean firstRowZero = false;
        boolean firstColumnZero = false;
 
        //set first row and column zero or not
        for(int i=0; i<matrix.length; i++){
            if(matrix[i][0] == 0){
                firstColumnZero = true;
                break;
            }
        }
 
        for(int i=0; i<matrix[0].length; i++){
            if(matrix[0][i] == 0){
                firstRowZero = true;
                break;
            }
        }
 
        //mark zeros on first row and column
        for(int i=1; i<matrix.length; i++){
            for(int j=1; j<matrix[0].length; j++){
                if(matrix[i][j] == 0){
                   matrix[i][0] = 0;
                   matrix[0][j] = 0;
                }
            }
        }
 
        //use mark to set elements
        for(int i=1; i<matrix.length; i++){
            for(int j=1; j<matrix[0].length; j++){
                if(matrix[i][0] == 0 || matrix[0][j] == 0){
                   matrix[i][j] = 0;
                }
            }
        }
 
        //set first column and row
        if(firstColumnZero){
            for(int i=0; i<matrix.length; i++)
                matrix[i][0] = 0;
        }
 
        if(firstRowZero){
            for(int i=0; i<matrix[0].length; i++)
                matrix[0][i] = 0;
        }
 
    }
}

18 thoughts on “LeetCode – Set Matrix Zeroes (Java)”

  1. int n=matrix.size();
    int m=matrix[0].size();
    int cols=1;
    for(int i=0;i<n;i++){
    if(matrix[i][0]==0){ cols=0;}

    for(int j=1;j=0;i–){
    for(int j=m-1;j>=1;j–){
    if(matrix[i][0]==0 || matrix[0][j]==0){
    matrix[i][j]=0;
    }
    } if(cols==0) {matrix[i][0]=0;}

    }

    for c++

  2. could someone explain me OVERALL IDEA what to do ? i just cant get it. really!!!!!!

    if have zero at 0:0, 0column and 0row will be marked zero.? so after whole matrix will be marked by 0s??
    or I can’t use modified matrix,only original?

    what if I start not from element 0:0 , but m-1:n-1 ? can I do this?

  3. You can do it with just three for loops using boolean arrays.

    void setZeros(int[][] matrix) {
    boolean[] row = new boolean[matrix.length];
    boolean[] column = new boolean[matrix[0].length];

    for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[0].length; j++) {
    if (matrix[i][j] == 0) {
    row[i] = true;
    column[j] = true;
    }
    }
    }

    // Nullify rows
    for (int i = 0; i < row.length; i++) {
    if (row[i]) {
    for (int j = 0; j < matrix[0].length; j++) {
    matrix[i][j] = 0;
    }
    }
    }

    // Nullify columns
    for (int j = 0; j < column.length; j++) {
    if (column[j]) {
    for (int i = 0; i < matrix.length; i++) {
    matrix[i][j] = 0;
    }
    }
    }
    }

  4. import java.util.LinkedList;
    import java.util.List;

    public class MakeZerosInMatrix {

    public static void main(String[] args) {
    int[][] array = {{0, 2, 3}, {4, 5, 6}, {2, 5, 0}};

    for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
    System.out.print(array[i][j] + " ");
    }
    System.out.println(" ");
    }
    List visitedRowIndex = new LinkedList();
    List visitedColumnIndex = new LinkedList();
    for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
    if (!visitedRowIndex.contains(i) && !visitedColumnIndex.contains(j) && array[i][j] == 0) {
    visitedColumnIndex.add(j);
    visitedRowIndex.add(i);
    for (int k = 0; k < array.length; k++) {
    array[k][j] = 0;
    }
    for (int k = 0; k < array.length; k++) {
    array[i][k] = 0;
    }
    }
    }
    System.out.println(" ");
    }

    for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
    System.out.print(array[i][j] + " ");
    }
    System.out.println(" ");
    }
    }
    }

  5. the last lines are getting messed up in code-editor Here it is:


    for(int n : coord)
    {
    int j=n%10;
    int i=n/10; int k=0;
    int l=0;
    while(k<row)

    {

    arr1[k][j]=0;

    k++;

    }

    while(l<column)

    {
    arr1[i][l]=0;
    l++;
    }
    }

  6. public class SetZeroMatrix {

    static Scanner in = new Scanner(System.in);

    public static void main(String[] args) {

    System.out.println(“Enter size of matrix”);

    int s = in.nextInt();

    int[][] a = new int[s][s];

    int q=0;

    System.out.println(“Enter the matrix”);

    for(int i=0;i<s;i++){

    for(int j=0;j<s;j++){

    a[i][j] = in.nextInt();

    }

    }

    //Algorithm marking zero positions

    for(int i=0;i<s;i++){

    for(int j=0;j<s;j++){

    if(a[i][j]==0){

    a[i][j]=9999;

    }

    }

    }

    //Algorithm setting rows and columns as zeros

    for(int i=0;i<s;i++){

    for(int j=0;j<s;j++){

    if(a[i][j]==9999){

    for(q=0;q<s;q++){

    a[i][q]=0;

    a[q][j]=0;

    }

    }

    }

    }

    //printing

    for(int i=0;i<s;i++){

    for(int j=0;j<s;j++){

    System.out.print(a[i][j]);

    }

    System.out.println("");

    }

    }

    }

  7. I think you are not considering the case, that the first row or first column is not 0 and therefore should contain the values at the end that it contained at the beginning.
    In your solution the current values of row and column 0 would be overwritten.

  8. public class SetMatrixZeros {

    public static int[][] setMatrixZeros(int[][] array) {

    if(array.length == 0) {
    return array;
    }

    int numColumns = array[0].length;
    int numrows = array.length;

    //we just need to keep track of what row and column sho //uld be 0
    Set rows = new HashSet();
    Set columns = new HashSet();

    for(int i = 0; i < numrows ; i++) {
    for(int j = 0 ; j < numColumns ; j++) {
    if(array[i][j] == 0) {
    rows.add(i);
    columns.add(j);
    }
    }
    }

    //now set rows and columns to 0s
    for(int row : rows) {
    for(int i = 0 ; i < numColumns ; i++) {
    array[row][i] = 0;
    }
    }

    for(int column : columns) {
    for(int i = 0 ; i < numrows ; i++) {
    array[i][column] = 0;
    }
    }
    return array;
    }
    }

  9. Here is my intuitive solution accepted by LeetCode judge :

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

  10. Your solution takes O(n*m(n+m)) if the matrix is full of zeros, which is O(n^3) if n==m. Wang’s solution is wiser and takes O(n*m).

  11. I think this is a more elegant solution and O(n2)

    public void clearColumnRows(int [][] m, int i, int j)
    {
    if(j >= m[0].length)
    {
    j = 0;
    i += 1;
    }
    if(i >= m.length)
    {
    return;
    }
    if(m[i][j] != 0)
    {
    clearColumnRows(m, i, j + 1);
    }
    else {
    clearColumnRows(m, i, j + 1);
    for(int x = 0; x < m.length; x++)
    {
    m[x][j] = 0;
    }
    for(int x = 0; x < m[0].length; x++)
    {
    m[i][x] = 0;
    }
    }
    }

Leave a Comment