Set row or column in matrix to zero, when at least one element in the row or column is zero.

Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.

C++:
01 void setZero(vector <int*>& M, int m, int n)
02 {
03     vector <int> row(m,1);
04     vector <int> col(n,1);
05     for(int i=0;i<m;i++){
06         for(int j=0;j<n;j++){
07             if(M[i][j]==0){
08                 row[i]=0;
09                 col[j]=0;
10             }
11         }
12     }
13     for(int i=0;i<m;i++)
14         for(int j=0;j<n;j++)
15             M[i][j]*=row[i]*col[j];
16 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s