稀疏矩阵是其中大多数元素为0的矩阵。其示例如下。
下面给出的矩阵包含5个零。由于零的数量大于矩阵元素的一半,因此它是稀疏矩阵。
5 0 0 3 0 1 0 0 9
实现稀疏矩阵的程序如下。
#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<<"矩阵为:"<<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; }
输出结果
矩阵为: 0 0 9 5 0 8 7 0 0 The number of zeros in the matrix are 5 This is a sparse matrix
在上面的程序中,嵌套的for循环用于计算矩阵中的零个数。使用以下代码段对此进行了演示。
for (i = 0; i < row; ++i) { for (j = 0; j < col; ++j) { if (a[i][j] == 0) count++; } }
找到零的数量后,使用嵌套的for循环显示矩阵。如下所示。
cout<<"矩阵为:"<<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;