Ma trận thưa (sparse matrix) là ma trận có hơn 2/3 phần tử là 0. Kiểm tra bằng cách đếm số phần tử 0, so sánh với 2/3 tổng số phần tử.

Ví dụ
#include <iostream>
#include <cmath>
#define MAX 5
using namespace std;
bool isSparseMatrix(int arr[][MAX], int m, int n) {
int counter = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j <n; j++)
if (arr[i][j] == 0)
counter++;
return (counter > (2*(m * n) / 3));
}
int main() {
int matrix[MAX][MAX] = {
{0, 2, 0, 0, 0},
{8, 0, 0, 0, 0},
{0, 3, 0, 0, 0},
{0, 9, 0, 3, 0},
{0, 0, 0, 0, 4}
};
if(isSparseMatrix(matrix, MAX, MAX)){
cout << "This is sparse matrix";
} else {
cout << "This is not sparse matrix";
}
}
Kết quả
This is sparse matrix