여기에서 행렬이 희소인지 여부를 확인하는 방법을 살펴보겠습니다. 희소 행렬은 대부분의 요소가 0인 행렬입니다. 희소 행렬의 정의는 요소의 2/3가 0이면 희소 행렬로 표시됩니다. 다음은 희소 행렬의 예입니다.

이를 확인하기 위해 행렬의 0 개수를 세고 해당 개수가 전체 요소의 2/3보다 크면 희소입니다.
예
#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";
}
} 출력
This is sparse matrix