Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Php Program to Check if a given matrix is sparse or not

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 sparse. 
Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix,


Input : 1 0 3
        0 0 4
        6 0 0
Output : Yes
There are 5 zeros. This count
is more than half of matrix

Input : 1 2 3
        0 7 8
        5 0 7 
Output: No 

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, we return true. 


// PHP code to check if a matrix is
// sparse.
$MAX = 100;
function isSparse( $array, $m, $n)
    $counter = 0;
    // Count number of zeros
    // in the matrix
    for ($i = 0; $i < $m; ++$i)
        for ($j = 0; $j < $n; ++$j)
            if ($array[$i][$j] == 0)
    return ($counter > (($m * $n) / 2));
    // Driver Code
    $array = array(array(1, 0, 3),
                   array(0, 0, 4),
                   array(6, 0, 0));
    $m = 3;
    $n = 3;
    if (isSparse($array, $m, $n))
        echo "Yes";
        echo "No";
// This code is contributed by anuj_67.



Time Complexity: O(n*m)

Auxiliary Space: O(1)

Please refer complete article on Check if a given matrix is sparse or not for more details!

My Personal Notes arrow_drop_up
Last Updated : 30 Jun, 2022
Like Article
Save Article
Similar Reads
Related Tutorials