// A sparse matrix is a matrix in which the majority of elements are zero.
public class Main {
// Check if a matrix is sparse
static boolean isSparse(int[][] matrix) {
int zeroCount = 0;
int rows = matrix.length;
int cols = matrix[0].length;
// Count zeros
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 0) {
zeroCount++;
}
}
}
// A matrix is sparse if more than half of its elements are zero
return zeroCount > (rows * cols) / 2;
}
public static void main(String[] args) {
int[][] matrix = {
{2, 0, 5, 0},
{0, 4, 0, 0},
{0, 8, 0, 9}
};
if (isSparse(matrix)) {
System.out.println("Matrix is sparse");
} else {
System.out.println("Matrix is not sparse");
}
}
}
/*
run:
Matrix is sparse
*/