Ma trận thưa (Sparse Matrix) là ma trận có phần lớn phần tử bằng 0. Ví dụ ma trận 3x3 dưới đây có 5 số 0 (nhiều hơn nửa 9 phần tử) → là ma trận thưa.
5 0 0 3 0 1 0 0 9
Ví dụ
#include <iostream>
using namespace std;
int main() {
int a[10][10] = { {0, 0, 9}, {5, 0, 8}, {7, 0, 0} };
int i, j, count = 0;
int row = 3, col = 3;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
if (a[i][j] == 0)
count++;
}
}
cout << "The matrix is:" << endl;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j)
cout << a[i][j] << " ";
cout << endl;
}
cout << "The number of zeros in the matrix are " << count << endl;
if (count > ((row * col) / 2))
cout << "This is a sparse matrix" << endl;
else
cout << "This is not a sparse matrix" << endl;
return 0;
}
Kết quả
The matrix is: 0 0 9 5 0 8 7 0 0 The number of zeros in the matrix are 5 This is a sparse matrix
Đếm số lượng số 0
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
if (a[i][j] == 0)
count++;
}
}
Hiển thị ma trận
cout << "The matrix is:" << endl;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j)
cout << a[i][j] << " ";
cout << endl;
}
Kiểm tra và thông báo
cout << "The number of zeros in the matrix are " << count << endl;
if (count > ((row * col) / 2))
cout << "This is a sparse matrix" << endl;
else
cout << "This is not a sparse matrix" << endl;