Sunday 17 July 2016

Set Matrix Zeros

Given an m x n matrix of 0s and 1s, if an element is 0, set its entire row and column to 0.
Do it in place.
Example
The matrix
1 0 0 1
0 0 1 0
0 0 0 0
should be changed to following
1 1 1 1
1 1 1 1
1 0 1 1
Approach: Use the first row and first column to store the row and column indices which has zero in them. But before updating the first row and the first column, find if they have a zero in the first row and the first column or not to later update the row and the column to zeros.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**  
  * @input A : 2D integer array  
  * @input n11 : Integer array's ( A ) rows  
  * @input n12 : Integer array's ( A ) columns  
  *  
  * @Output Void. Just modifies the args passed by reference  
  */  
 void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) {  
   int firstRowZero = 0, firstColumnZero = 0, i, j;  
   for(i = 0 ; i < matrixRowSize; i++){  
     if(matrix[i][0] == 0){  
       firstColumnZero = 1;  
       break;  
     }  
   }  
   for(i = 0 ; i < matrixColSize; i++){  
     if(matrix[0][i] == 0){  
       firstRowZero = 1;  
       break;  
     }  
   }  
   for(i = 1; i < matrixRowSize; i++){  
     for(j = 1; j < matrixColSize; j++){  
       if(matrix[i][j] == 0){  
         matrix[i][0] = 0;  
         matrix[0][j] = 0;  
       }  
     }  
   }  
   for(i = 1; i < matrixRowSize; i++){  
     if(matrix[i][0] == 0){  
       for(j = 1; j < matrixColSize; j++)  
         matrix[i][j] = 0;  
     }  
   }  
   for(i = 1; i < matrixColSize; i++){  
     if(matrix[0][i] == 0){  
       for(j = 1; j < matrixRowSize; j++)  
         matrix[j][i] = 0;  
     }  
   }  
   if(firstRowZero){  
     for(j = 0; j < matrixColSize; j++)  
       matrix[0][j] = 0;  
   }  
   if(firstColumnZero){  
     for(j = 0; j < matrixRowSize; j++)  
       matrix[j][0] = 0;  
   }  
 }
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive