How to change all elements of row i and column j in a binary matrix to 0 if cell[i, j] is 0 with C

1 Answer

0 votes
#include <stdio.h>

#define COLS 6

void changeRowColumn(int matrix[][COLS], int rows, int cols, int row, int col) {
    // -1 = different from the existing zeros
    
    for (int j = 0; j < cols; j++) {
        if (matrix[row][j] != 0) {
            matrix[row][j] = -1;
        }
    }
    
    for (int i = 0; i < rows; i++) {
        if (matrix[i][col] != 0) {
            matrix[i][col] = -1;
        }
    }
}

void changeBinaryMatrix(int matrix[][COLS], int rows, int cols) {
    if (rows == 0 || cols == 0) {
        return;
    }
    
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (matrix[i][j] == 0) {
                changeRowColumn(matrix, rows, cols, i, j);
            }
        }
    }
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (matrix[i][j] == -1) {
                matrix[i][j] = 0;
            }
        }
    }
}

void printMatrix(int matrix[][COLS], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrix[][COLS] = {
            { 1, 1, 0, 1, 1, 1 },
            { 1, 1, 1, 1, 1, 1 },
            { 1, 1, 0, 1, 1, 1 },
            { 1, 1, 1, 1, 1, 1 },
            { 1, 0, 1, 1, 1, 1 }
    };
 
    int rows = (sizeof(matrix) / sizeof(matrix[0]));
    int cols = (sizeof(matrix) / sizeof(matrix[0][0])) / rows;
    
    changeBinaryMatrix(matrix, rows, cols);

    printMatrix(matrix, rows, cols);

    return 0;
}




/*
run:

0 0 0 0 0 0 
1 0 0 1 1 1 
0 0 0 0 0 0 
1 0 0 1 1 1 
0 0 0 0 0 0 

*/

 



answered Jan 21, 2024 by avibootz
...