Learn-dsa..in 30 days!



























CC-9 : Check if matrix is a sparse matrix.

Description:

A sparse matrix, is a matrix where greater that half of total elements of matrix are 0. Given input matrix mat, check if it is a sparse matrix.

Test cases and expected outputs:

Input Expected outputs
mat = {
{1,0,0},
{1,0,0},
{1,0,0}}
The matrix is a Sparse Matrix.
mat= {
{0,2,4,0},
{0,1,2,0},
{0,3,1,0}}
The matrix is *not* a Sparse Matrix.
mat = {
{1,0},
{0,0},
{1,0},
{0,1}};
The matrix is a Sparse Matrix.
mat = {
{1,1,0,0},
{0,1,1,0},
{0,0,1,1},
{0,0,0,1}};
The matrix is a Sparse Matrix.

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Initialize an int variable size with value equal to count of total elements in mat.
Initialize an int variable zeroCnt to hold the count of 0s found in mat.
Iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
If mat[rIdx][cIdx] == 0 negative, increment zeroCnt by 1.
If zeroCnt > size/2, return true from the program as the matrix is a sparse matrix.
Once above loops are completed, and the program has not exited then this indicates zeroCnt is less than or equal to size/2, so return false from the program as the matrix is not a sparse matrix.

Code:

public boolean matArraySparseMatrix(int[][] mat) throws Exception{
	int size = 	mat.length * mat[0].length;
	int zeroCnt=0;
	for (int rIdx=0; rIdx < mat.length; rIdx++) {
		for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
		  	 if (mat[rIdx][cIdx] == 0) {
		  		zeroCnt++;
			 }
		  	 if (zeroCnt > size/2) {
		  		 return true;
		  	 }
		  }		
	}
	return false;
}

Click here to download and run code and test cases !