Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
写一个函数处理一个MxN的矩阵,如果矩阵中某个元素为0,那么把它所在的行和列都置为0.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
void zero(int a[][4], int m, int n){
bool row[m], col[n];
memset(row, false, sizeof(row));
memset(col, false, sizeof(col));
for(int i=0; i<m; ++i)
for(int j=0; j<n; ++j)
if(a[i][j] == 0){
row[i] = true;
col[j] = true;
}
for(int i=0; i<m; ++i)
for(int j=0; j<n; ++j)
if(row[i] || col[j])
a[i][j] = 0;
}
int main()
{
int m=4,n=4;
int a[][4]={{1,2,3,4},{5,6,7,8},{9,0,11,12},{13,14,15,16}};
zero(a, m, n);
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
system("pause");
return 0;
}