Set Matix Zero
/***
Write a algorithm such that if an element in an M*N matrix is 0, its entire row and column are set to 0.
***/
/**
two sets store the zero column when the first scan. And set zero when the second scan. **/
#include<iostream>
#include<set>
using namespace std;
void set0Matrix(int (*a)[5], int sz) {
set<int> col, row;
set<int>::iterator it1;
set<int>::iterator it2;
int i,j;
//first scan
for(i=0; i<sz; i++) {
for(j=0; j<sz; j++) {
if(a[i][j] == 0) {
row.insert(i);
col.insert(j);
}
}
}
//second scan
for(i = 0, it1 = row.begin(); i<sz && it1 != row.end(); i++) {
if(i == *it1) {
for(j = 0; j < sz; j++)
a[i][j] = 0;
it1++;
} else {
for(j = 0, it2 = col.begin(); j < sz && it2 != col.end(); j++) {
if(j == *it2) {
a[i][j] = 0;
it2++;
}
}
}
}
}
void print(int (*a)[5], int sz) {
for(int i=0; i<sz; i++) {
for(int j=0; j<sz; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
void main() {
int a[5][5] = {{1,2,0,5,2},{1,2,3,5,2},{1,2,2,5,2},{1,2,4,0,2},{0,2,1,5,2}};
print(a, 5);
cout<<endl;
set0Matrix(a, 5);
print(a, 5);
}
Comments
Post a Comment