Given a matrix arr[][] of size N * M, the task is to print the matrix after removing all rows and columns from the matrix which consists of 0s only.
Examples:
Input: arr[][] ={ { 1, 1, 0, 1 }, { 0, 0, 0, 0 }, { 1, 1, 0, 1}, { 0, 1, 0, 1 } }Â
Output:Â
111Â
111Â
011Â
Explanation:Â
Initially, the matrix is as follows:Â
arr[][] = { { 1, 1, 0, 1 },Â
       { 0, 0, 0, 0 },Â
       { 1, 1, 0, 1 },Â
      { 0, 1, 0, 1 } }Â
Removing the 2nd row modifies the matrix to:Â
arr[][] = { { 1, 1, 0, 1 },Â
        { 1, 1, 0, 1 },Â
       { 0, 1, 0, 1 } }Â
Removing the 3rd column modifies the matrix to:Â
arr[][] = { { 1, 1, 1 },Â
        { 1, 1, 1 },Â
       { 0, 1, 1 } }ÂInput: arr={{0, 1}, {0, 1}}Â
Output:Â
1Â
1Â
Approach: The idea is to count the number of 0s in all the rows and columns of the matrix and check if any rows or columns consist only of 0s or not. If found to be true, then remove those rows or the columns of the matrix. Follow the steps below to solve the problem:
- Traverse the matrix and count 1s in rows and columns.
- Now, traverse over the loop again and check for the following:Â
- If the count of 1s is found to be 0 for any row, skip that row.
- If the count of 1s is found to be greater than 0 for any column, print that element.
Below is the implementation of the above approach:
C++
// C++ program for the above approach   #include <bits/stdc++.h>   using namespace std;         // Function to remove the rows or columns from   // the matrix which contains all 0s elements   void removeZeroRowCol(vector<vector< int > >& arr)   {             // Stores count of rows       int n = arr.size();             // col[i]: Stores count of 0s       // in current column       int col[n + 1] = { 0 };             // row[i]: Stores count of 0s       // in current row       int row[n + 1] = { 0 };             // Traverse the matrix       for ( int i = 0; i < n; ++i) {                 // Stores count of 0s           // in current row           int count = 0;                 for ( int j = 0; j < n; ++j) {                     // Update col[j]               col[j] += (arr[i][j] == 1);                     // Update count               count += (arr[i][j] == 1);           }                 // Update row[i]           row[i] = count;       }             // Traverse the matrix       for ( int i = 0; i < n; ++i) {                 // If all elements of           // current row is 0           if (row[i] == 0) {               continue ;           }           for ( int j = 0; j < n; ++j) {                     // If all elements of               // current column is 0               if (col[j] != 0)                   cout << arr[i][j];           }           cout << "\n" ;       }   }         // Driver Code   int main()   {       vector<vector< int > > arr = { { 1, 1, 0, 1 },                                    { 0, 0, 0, 0 },                                    { 1, 1, 0, 1 },                                    { 0, 1, 0, 1 } };             // Function Call       removeZeroRowCol(arr);       return 0;   } |
Java
// Java program for the above approach import java.io.*; class GFG{          // Function to remove the rows or columns from   // the matrix which contains all 0s elements   static void removeZeroRowCol( int arr[][])   {            // Stores count of rows       int n = arr.length;             // col[i]: Stores count of 0s       // in current column       int col[] = new int [n + 1 ];             // row[i]: Stores count of 0s       // in current row       int row[] = new int [n + 1 ];             // Traverse the matrix       for ( int i = 0 ; i < n; ++i)     {                    // Stores count of 0s           // in current row           int count = 0 ;                 for ( int j = 0 ; j < n; ++j)         {             if (arr[i][j] == 1 )                              // Update col[j]                   col[j] += 1 ;               else                 col[j] += 0 ;                   if (arr[i][j] == 1 )                              // Update count                       count += 1 ;               else                 count += 0 ;         }                 // Update row[i]           row[i] = count;       }             // Traverse the matrix       for ( int i = 0 ; i < n; ++i)     {                    // If all elements of           // current row is 0           if (row[i] == 0 )         {               continue ;           }           for ( int j = 0 ; j < n; ++j)         {                            // If all elements of               // current column is 0               if (col[j] != 0 )                   System.out.print(arr[i][j]);           }           System.out.println();       }   }   Â
// Driver Code   public static void main (String[] args)   {       int arr[][] = { { 1 , 1 , 0 , 1 },                       { 0 , 0 , 0 , 0 },                       { 1 , 1 , 0 , 1 },                       { 0 , 1 , 0 , 1 } };             // Function Call       removeZeroRowCol(arr);   } } Â
// This code is contributed by AnkThon |
Python3
# Python3 program for the above approach          # Function to remove the rows or columns from    # the matrix which contains all 0s elements    def removeZeroRowCol(arr) :               # Stores count of rows        n = len (arr)               # col[i]: Stores count of 0s        # in current column        col = [ 0 ] * (n + 1 )               # row[i]: Stores count of 0s        # in current row        row = [ 0 ] * (n + 1 )               # Traverse the matrix        for i in range (n) :                  # Stores count of 0s            # in current row            count = 0                   for j in range (n) :                      # Update col[j]                col[j] + = (arr[i][j] = = 1 )                      # Update count                count + = (arr[i][j] = = 1 )                  # Update row[i]            row[i] = count              # Traverse the matrix        for i in range (n) :                  # If all elements of            # current row is 0            if (row[i] = = 0 ) :               continue                         for j in range (n) :                      # If all elements of                # current column is 0                if (col[j] ! = 0 ) :                   print (arr[i][j], end = "")                         print ()                arr = [ [ 1 , 1 , 0 , 1 ],             [ 0 , 0 , 0 , 0 ],             [ 1 , 1 , 0 , 1 ],             [ 0 , 1 , 0 , 1 ] ]          # Function Call    removeZeroRowCol(arr) Â
# This code is contributed by divyeshrabadiya07 |
C#
// C# program for the above approach   using System; Â
class GFG{          // Function to remove the rows or columns from   // the matrix which contains all 0s elements   static void removeZeroRowCol( int [,] arr)   {            // Stores count of rows       int n = arr.GetLength(0);             // col[i]: Stores count of 0s       // in current column       int [] col = new int [n + 1];             // row[i]: Stores count of 0s       // in current row       int [] row = new int [n + 1];             // Traverse the matrix       for ( int i = 0; i < n ; ++i)     {                    // Stores count of 0s           // in current row           int count = 0;                 for ( int j = 0; j < n ; ++j)         {             if (arr[i, j] == 1)                              // Update col[j]                   col[j] += 1;               else                 col[j] += 0;                   if (arr[i, j] == 1)                              // Update count                       count += 1;               else                 count += 0;         }                 // Update row[i]           row[i] = count;       }             // Traverse the matrix       for ( int i = 0; i < n; ++i)     {                    // If all elements of           // current row is 0           if (row[i] == 0)         {               continue ;           }           for ( int j = 0; j < n; ++j)         {                            // If all elements of               // current column is 0               if (col[j] != 0)                   Console.Write(arr[i, j]);           }           Console.WriteLine();       }   }   Â
// Driver Code   public static void Main (String[] args)   {       int [,] arr = { { 1, 1, 0, 1 },                      { 0, 0, 0, 0 },                      { 1, 1, 0, 1 },                      { 0, 1, 0, 1 } };             // Function Call       removeZeroRowCol(arr);   } } Â
// This code is contributed by susmitakundugoaldanga |
Javascript
<script> // Javascript program to implement // the above approach Â
// Function to remove the rows or columns from  // the matrix which contains all 0s elements  function removeZeroRowCol(arr)  {            // Stores count of rows      let n = arr.length;             // col[i]: Stores count of 0s      // in current column      let col = Array.from({length: n+1}, (_, i) => 0);            // row[i]: Stores count of 0s      // in current row      let row = Array.from({length: n+1}, (_, i) => 0);            // Traverse the matrix      for (let i = 0; i < n; ++i)     {                    // Stores count of 0s          // in current row          let count = 0;                 for (let j = 0; j < n; ++j)         {             if (arr[i][j] == 1)                               // Update col[j]                  col[j] += 1;              else                 col[j] += 0;                    if (arr[i][j] == 1)                               // Update count                      count += 1;              else                 count += 0;         }                 // Update row[i]          row[i] = count;      }             // Traverse the matrix      for (let i = 0; i < n; ++i)     {                    // If all elements of          // current row is 0          if (row[i] == 0)         {              continue ;          }          for (let j = 0; j < n; ++j)         {                            // If all elements of              // current column is 0              if (col[j] != 0)                  document.write(arr[i][j]);          }          document.write( "<br/>" );      }  }  Â
// Driver Code Â
    let arr = [[ 1, 1, 0, 1 ],                      [ 0, 0, 0, 0 ],                      [ 1, 1, 0, 1 ],                      [ 0, 1, 0, 1 ]];             // Function Call      removeZeroRowCol(arr);    // This code is contributed by souravghosh0416. </script> |
111 111 011
Time complexity: O(N*M)
Auxiliary Space: O(N+M)
Another efficient approach: The idea is to mark all rows and columns that contain all zeros with some other special integer (a value that is not present in the matrix) to identify that we do not need that particular row or column and whenever we reach While iterating over the matrix on that particular integer we skip that cell because we assume that the cell has been removed while deletion of the row or column which has all zeros.
Follow the below steps to implement the idea:
- Iterate over all rows one by one and check if that particular row contains all zeros or not.
If, particular row contains all zeros then fill special integer to mark that row containing all zeros. - Iterate over all columns one by one and check if that particular column contains all zeros or not.
If, particular column contains all zeros then fill special integer to mark that column containing all zeros. - Iterate over the matrix and check if any particular cell is marked with special integer.
If yes, then skip that cell.
Otherwise, print that cell.
Below is the implementation of above approach:
C++
// C++ code to implement the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to mark all row and column // to special integer which contains all zeros void removeZeroRowCol(vector<vector< int > >& A) { Â
    int i, j, m, n;     m = A.size(); Â
    if (m != 0)         n = A[0].size(); Â
    // Traversing by row     for (i = 0; i < m; i++) {         for (j = 0; j < n; j++) { Â
            // If found that the complete row do             // not contain only zeros             if (A[i][j] == 1)                 break ;         } Â
        // If found that the complete row         // contain zero         if (j == n) {             for (j = 0; j < n; j++)                 A[i][j] = -1;         }     } Â
    // Traversing by column     for (i = 0; i < m; i++) {         for (j = 0; j < n; j++) { Â
            // If found that the complete column             // do not contain all zeros             if (A[j][i] == 1)                 break ;         } Â
        // If found that the complete column         // contain only zeros         if (j == n) {             for (j = 0; j < n; j++)                 A[j][i] = -1;         }     } } Â
// Function to print the matrix void print(vector<vector< int > >& A) { Â Â Â Â int i, j, m, n; Â Â Â Â m = A.size(); Â
    if (m != 0)         n = A[0].size(); Â
    // Taking a flag which helps us in printing     // the matrix because if we found that the above     // row is contain only zero then we won't go to next     // line otherwise there will be space between     // two consecutive rows     bool flag = false ; Â
    // Iterating over matrix     for (i = 0; i < m; i++) {         for (j = 0; j < n; j++) {             if (A[i][j] != -1) {                 cout << A[i][j]; Â
                // Making flag true if row get                 // printed                 flag = true ;             }         } Â
        // If row got printed then moving to the         // next line         if (flag) {             cout << endl;             flag = !flag;         }     } } Â
// Driver code int main() { Â
    // Initializing matrix     vector<vector< int > > arr{ { 1, 1, 0, 1 },                               { 0, 0, 0, 0 },                               { 1, 1, 0, 1 },                               { 0, 1, 0, 1 } }; Â
    // Function calling     removeZeroRowCol(arr); Â
    // Function to print the matrix     print(arr); Â
    return 0; } |
Java
/*package whatever //do not write package name here */ Â
import java.io.*; Â
class GFG { Â Â // Java code to implement the above approach Â
  // Function to mark all row and column   // to special integer which contains all zeros   static void removeZeroRowCol( int [][] A)   { Â
    int i = 0 , j = 0 , m = A.length, n = 0 ; Â
    if (m != 0 )       n = A[ 0 ].length; Â
    // Traversing by row     for (i = 0 ; i < m; i++) {       for (j = 0 ; j < n; j++) { Â
        // If found that the complete row do         // not contain only zeros         if (A[i][j] == 1 )           break ;       } Â
      // If found that the complete row       // contain zero       if (j == n) {         for (j = 0 ; j < n; j++)           A[i][j] = - 1 ;       }     } Â
    // Traversing by column     for (i = 0 ; i < m; i++) {       for (j = 0 ; j < n; j++) { Â
        // If found that the complete column         // do not contain all zeros         if (A[j][i] == 1 )           break ;       } Â
      // If found that the complete column       // contain only zeros       if (j == n) {         for (j = 0 ; j < n; j++)           A[j][i] = - 1 ;       }     }   } Â
  private static void e() {   } Â
  // Function to print the matrix   static void print( int [][] A)   {     int i = 0 , j = 0 , m = 0 , n = 0 ;     m = A.length; Â
    if (m != 0 )       n = A[ 0 ].length; Â
    // Taking a flag which helps us in printing     // the matrix because if we found that the above     // row is contain only zero then we won't go to next     // line otherwise there will be space between     // two consecutive rows     boolean flag = false ; Â
    // Iterating over matrix     for (i = 0 ; i < m; i++) {       for (j = 0 ; j < n; j++) {         if (A[i][j] != - 1 ) {           System.out.print(A[i][j]); Â
          // Making flag true if row get           // printed           flag = true ;         }       } Â
      // If row got printed then moving to the       // next line       if (flag) {         System.out.println();         flag = !flag;       }     }   } Â
  // Driver Code   public static void main(String args[])   {     // Initializing matrix     int [][] arr = { { 1 , 1 , 0 , 1 },                    { 0 , 0 , 0 , 0 },                    { 1 , 1 , 0 , 1 },                    { 0 , 1 , 0 , 1 } }; Â
    // Function calling     removeZeroRowCol(arr); Â
    // Function to print the matrix     print(arr);   } } Â
// This code is contributed by shinjanpatra |
Python3
# Python code to implement the above approach Â
# Function to mark all row and column # to special integer which contains all zeros def removeZeroRowCol(A): Â
    m = len (A) Â
    if (m ! = 0 ):         n = len (A[ 0 ]) Â
    i,j = 0 , 0 Â
    # Traversing by row     for i in range (m):         for j in range (n): Â
            # If found that the complete row do             # not contain only zeros             if (A[i][j] = = 1 ):                 break                 # If found that the complete row         # contain zero         if (j = = n - 1 ):             for j in range (n):                 A[i][j] = - 1 Â
    # Traversing by column     for i in range (m):         for j in range (n):             # If found that the complete column             # do not contain all zeros             if (A[j][i] = = 1 ):                 break Â
        # If found that the complete column         # contain only zeros         if (j = = n - 1 ):             for j in range (n):                 A[j][i] = - 1      # Function to print the matrix def Print (A): Â
    m = len (A) Â
    if (m ! = 0 ):         n = len (A[ 0 ]) Â
    # Taking a flag which helps us in printing     # the matrix because if we found that the above     # row is contain only zero then we won't go to next     # line otherwise there will be space between     # two consecutive rows     flag = False Â
    # Iterating over matrix     for i in range (m):         for j in range (n):             if (A[i][j] ! = - 1 ):                 print (A[i][j],end = "") Â
                # Making flag true if row get                 # printed                 flag = True Â
        # If row got printed then moving to the         # next line         if (flag):             print ()             flag = False if (flag = = True ) else True      Â
# Driver code Â
# Initializing matrix arr = [ [ 1 , 1 , 0 , 1 ], Â Â Â Â Â Â Â Â [ 0 , 0 , 0 , 0 ], Â Â Â Â Â Â Â Â [ 1 , 1 , 0 , 1 ], Â Â Â Â Â Â Â Â [ 0 , 1 , 0 , 1 ] ] Â
# Function calling removeZeroRowCol(arr) Â
# Function to print the matrix Print (arr) Â
# This code is contributed by shinjanpatra |
C#
using System; using System.Collections.Generic; Â
class GFG { Â Â // Java code to implement the above approach Â
  // Function to mark all row and column   // to special integer which contains all zeros   static void removeZeroRowCol( int [,] A)   { Â
    int i = 0, j = 0, m = A.GetLength(0), n = 0; Â
    if (m != 0)       n = A.GetLength(1); Â
    // Traversing by row     for (i = 0; i < m; i++) {       for (j = 0; j < n; j++) { Â
        // If found that the complete row do         // not contain only zeros         if (A[i,j] == 1)           break ;       } Â
      // If found that the complete row       // contain zero       if (j == n) {         for (j = 0; j < n; j++)           A[i,j] = -1;       }     } Â
    // Traversing by column     for (i = 0; i < m; i++) {       for (j = 0; j < n; j++) { Â
        // If found that the complete column         // do not contain all zeros         if (A[j,i] == 1)           break ;       } Â
      // If found that the complete column       // contain only zeros       if (j == n) {         for (j = 0; j < n; j++)           A[j,i] = -1;       }     }   } Â
  private static void e() {   } Â
  // Function to print the matrix   static void print( int [,] A)   {     int i = 0, j = 0, m = 0, n = 0;     m = A.GetLength(0); Â
    if (m != 0)       n = A.GetLength(1); Â
    // Taking a flag which helps us in printing     // the matrix because if we found that the above     // row is contain only zero then we won't go to next     // line otherwise there will be space between     // two consecutive rows     bool flag = false ; Â
    // Iterating over matrix     for (i = 0; i < m; i++) {       for (j = 0; j < n; j++) {         if (A[i,j] != -1) {           Console.Write(A[i,j]); Â
          // Making flag true if row get           // printed           flag = true ;         }       } Â
      // If row got printed then moving to the       // next line       if (flag) {         Console.WriteLine();         flag = !flag;       }     }   } Â
  // Driver Code   public static void Main( string [] args)   {     // Initializing matrix     int [,] arr = { { 1, 1, 0, 1 },                    { 0, 0, 0, 0 },                    { 1, 1, 0, 1 },                    { 0, 1, 0, 1 } }; Â
    // Function calling     removeZeroRowCol(arr); Â
    // Function to print the matrix     print(arr);   } } Â
// This code is contributed by phasing17 |
Javascript
// JS code to implement the above approach Â
// Function to mark all row and column // to special integer which contains all zeros function removeZeroRowCol(A) { Â Â Â Â let m = A.length Â
    if (m != 0)         n = A[0].length          let i = 0, j = 0 Â
    // Traversing by row     for (i = 0; i < m; i++)     {         for (j = 0; j < n; j++)         { Â
            // If found that the complete row do             // not contain only zeros             if (A[i][j] == 1)                 break         }         // If found that the complete row         // contain zero         if (j == n-1)             for (j = 0; j < n; j++)                 A[i][j] = -1     } Â
    // Traversing by column     for (i = 0; i < m; i++)     {         for (j = 0; j < n; j++)         {             // If found that the complete column             // do not contain all zeros             if (A[j][i] == 1)                 break         }         // If found that the complete column         // contain only zeros         if (j == n-1)             for (j = 0; j < n; j++)                 A[j][i] = -1     } }      // Function to print the matrix function Print(A) {     let m = A.length Â
    if (m != 0)         n = A[0].length Â
    // Taking a flag which helps us in printing     // the matrix because if we found that the above     // row is contain only zero then we won't go to next     // line otherwise there will be space between     // two consecutive rows     flag = false Â
    // Iterating over matrix     for (i = 0; i < m; i++)     {         for (j = 0; j < n; j++)         {             if (A[i][j] != -1)             {                 process.stdout.write(A[i][j] + "" ) Â
                // Making flag true if row get                 // printed                 flag = true             }         } Â
        // If row got printed then moving to the         // next line         if (flag)         {             console.log()             flag = !flag         }     } } Â
// Driver code Â
// Initializing matrix let arr = [ [ 1, 1, 0, 1 ], Â Â Â Â Â Â Â Â [ 0, 0, 0, 0 ], Â Â Â Â Â Â Â Â [ 1, 1, 0, 1 ], Â Â Â Â Â Â Â Â [ 0, 1, 0, 1 ] ] Â
// Function calling removeZeroRowCol(arr) Â
// Function to print the matrix Print(arr) Â
// This code is contributed by phasing17 |
111 111 011
Time complexity: O(N*M)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!