ในบทความนี้จะตรวจสอบว่า Matrix เป็น Sparse หรือไม่ Sparse Matrix คือ Matrix ที่ Element ส่วนใหญ่เป็น 0 นิยาม: ถ้า 2/3 ของ Elements เป็น 0 ถือว่า Sparse Matrix
ตัวอย่าง Sparse Matrix:

วิธีตรวจสอบ: นับจำนวน 0 ใน Matrix ถ้ามากกว่า 2/3 ของ Total Elements คือ Sparse
ตัวอย่างโค้ด C++
#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