Problem
Set elements to zero if an element in the same row or col is zero
Solution
#include <iostream>
using namespace std;
void set_mat_zero(int mat[5][4], int row, int col)
{
int *flag_row = new int[row];
int *flag_col = new int[col];
int i, j;
for(i=0; i< row; i++){
flag_row[i] = 1;
}
for(j=0; j < col; j++){
flag_col[j] = 1;
}
for(i=0; i < row; i++){
for(j=0; j< col; j++){
if(mat[i][j] == 0){
flag_row[i] = 0;
flag_col[j] = 0;
}
}
}
for(i=0; i < row; i++){
for(j=0; j< col; j++){
mat[i][j] *= flag_row[i]*flag_col[j];
}
}
}
int main(int argc, char* argv[])
{
int mat[5][4] = {
{1, 2, 3, 4},
{1, 0, 3, 4},
{1, 2, 3, 4},
{1, 2, 0, 4},
{1, 2, 3, 4}
};
set_mat_zero(mat, 5, 4);
for(int i=0; i<5; i++){
for(int j=0; j<4; j++){
cout << mat[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
1 0 0 4
0 0 0 0
1 0 0 4
0 0 0 0
1 0 0 4