Question:
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
Solution:
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
Solution:
#include <iostream> #include <string.h> using namespace std; void transform(int **data, int M,int N){ int *prev = new int[N]; for(int i=0;i<N;++i) prev[i]=1; for(int i=0;i<M;++i){ bool setrow = false; for(int j=0;j<N;++j){ bool setcol=false; if( prev[j] == 1 && data[i][j] == 0 ){ prev[j] = 0; setrow = true; setcol = true; } else if (prev[j]==0 && data[i][j] ){ data[i][j] = 0; } if (setcol){ for(int k=i;k>=0;--k){ data[k][j]=0; } } } if (setrow){ for(int k=0;k<N;++k){ data[i][k] = 0; } } } delete []prev; } void print(int **data, int M, int N){ for(int i=0;i<M;++i){ for(int j=0;j<N;++j){ cout<<data[i][j]<<" "; } cout<<endl; } } int main() { int **data; data = new int* [4]; for(int i=0;i<4;++i){ data[i] = new int[5]; } for(int i=0;i<4;++i) for(int j=0;j<5;++j) data[i][j]=1; data[0][3] = 0; data[1][2] = 0; data[2][3] = 0; print(data,4,5); transform(data,4,5); cout<<"------------------"<<endl; print(data,4,5); //release memory for(int i=0;i<5;++i){ delete[] data[i]; } delete[] data; return 0; }