Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Teach Your Child To Read

Disclosure: My content contains affiliate links.

31,649 questions

41,702 answers

573 users

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]
   
*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered 6 days ago by avibootz
...