Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Determine if a given Matrix is a Sparse Matrix

  • Last Updated : 11 Nov, 2020

A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is called a sparse matrix. So, we aim to count the number of 0s present in the matrix. If they are more than half of the elements in the matrix then print YES, else NO as output.

Examples:

Input:  1 0 3
        0 0 4
        6 0 0
Output: Yes
Explaination:There are 5 zeros in the matrix which 
          is more than half of the matrix size.

Input:  1 2 3
        0 7 8
        5 0 7 
Output: No 
Explaination:There are 2 zeros in the matrix which 
             is less than half of the matrix size.

 

To check whether a matrix is a sparse matrix we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2 then print Yes else No. There are two approaches to do so.

In this approach, we will check whether a matrix is a sparse matrix or not.



  1. Take the matrix.
  2. Traverse the matrix’s element one by one and counting the number of zeros.
  3. Checking if the count is more than (m*n)/2, if yes else no.

Below is the implementation of the above approach:

Java




// Java Program to Determine if a given
// Matrix is a Sparse Matrix
  
// Importing Libraries
import java.io.*;
  
class GFG {
  
    // Driver Function
    public static void main(String args[])
    {
        // Initialising and declaring
        // variables and array
  
        int array[][]
            = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } };
  
        int m = 3;
        int n = 3;
        int counter = 0;
  
        // Count number of zeros in the matrix
  
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                if (array[i][j] == 0)
                    ++counter;
  
        // Printing result
  
        if (counter > ((m * n) / 2))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Output
Yes

Time Complexity: O(m*n)

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :