How to set every row and column in a matrix to 0 if that row or column contains a 0 in Java

1 Answer

0 votes
import java.util.Arrays;

public class MatrixZeroerIfRowColZero_Java {
    public static void setZeros(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;

        boolean hasZeroInFirstRow = false;
        boolean hasZeroInFirstCol = false;

        for (int j = 0; j < cols; j++) {
            if (matrix[0][j] == 0) {
                hasZeroInFirstRow = true;
                break;
            }
        }

        for (int i = 0; i < rows; i++) {
            if (matrix[i][0] == 0) {
                hasZeroInFirstCol = true;
                break;
            }
        }

        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }

        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }

        if (hasZeroInFirstRow) {
            Arrays.fill(matrix[0], 0);
        }

        if (hasZeroInFirstCol) {
            for (int i = 0; i < rows; i++) {
                matrix[i][0] = 0;
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {{1, 0, 1, 1, 0},
                          {0, 1, 1, 1, 0},
                          {1, 1, 1, 1, 1},
                          {1, 0, 1, 1, 1},
                          {1, 1, 1, 1, 1}};

        setZeros(matrix);

        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}

   
    
/*
run:
   
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 1, 1, 0]
[0, 0, 0, 0, 0]
[0, 0, 1, 1, 0]
   
*/

 



answered Jul 10, 2024 by avibootz
...