Thursday 5 November 2015

Write an program such that if an element in an NxN matrix is 0, its entire row and column is set to 0.



Its simple just you need to keep track in two arrays all the rows with zeros and all the columns with zeros. You then make a second pass of the matrix and set a cell to zero if its row or column is zero.


Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class MatrixProblem {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int m[][] = { { 1, 2, 0 }, { 3, 4, 5 }, { 6, 7, 8 } };  
           setZeros(m);  
      }  
      public static void setZeros(int[][] matrix) {  
           int[] row = new int[matrix.length];  
           int[] column = new int[matrix[0].length];  
           // Store the row and column index with value 0  
           for (int i = 0; i < matrix.length; i++) {  
                for (int j = 0; j < matrix[0].length; j++) {  
                     if (matrix[i][j] == 0) {  
                          row[i] = 1;  
                          column[j] = 1;  
                     }  
                }  
           }  
           // Set arr[i][j] to 0 if either row i or column j has a 0  
           for (int i = 0; i < matrix.length; i++) {  
                for (int j = 0; j < matrix[0].length; j++) {  
                     if ((row[i] == 1 || column[j] == 1)) {  
                          matrix[i][j] = 0;  
                     }  
                }  
           }  
           for (int i = 0; i < matrix.length; i++) {  
                for (int j = 0; j < matrix.length; j++) {  
                     System.out.print(matrix[i][j] + " ");  
                }  
                System.out.println("\n");  
           }  
      }  
 }  


Output:-


 0 0 0   
 3 4 0   
 6 7 0   


Enjoy Programming.

No comments:

Post a Comment