C ++程序检查它是否是稀疏矩阵
稀疏矩阵是其中大多数元素为0的矩阵。换句话说,如果矩阵中超过一半的元素为0,则称为稀疏矩阵。例如-
下面给出的矩阵包含5个零。由于零的数量大于矩阵元素的一半,因此它是稀疏矩阵。
1 0 2 5 0 0 0 0 9
检查其是否为稀疏矩阵的程序如下。
示例
#include<iostream> using namespace std; int main () { int a[10][10] = { {2, 0, 0} , {0, 3, 8} , {0, 9, 0} }; int i, j, count = 0; int r = 3, c = 3; for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { if (a[i][j] == 0) count++; } } cout<<"矩阵为:"<<endl; for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { cout<<a[i][j]<<" "; } cout<<endl; } cout<<"There are "<<count<<" zeros in the matrix"<<endl; if (count > ((r * c)/ 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl; return 0; }
输出结果
矩阵为: 2 0 0 0 3 8 0 9 0 There are 5 zeros in the matrix This is a sparse matrix
在上面的程序中,嵌套的for循环用于计算矩阵中的零个数。使用以下代码段对此进行了演示。
for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { if (a[i][j] == 0) count++; } }
找到零的数量后,使用嵌套的for循环显示矩阵。这如下所示-
cout<<"矩阵为:"<<endl; for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { cout<<a[i][j]<<" "; } cout<<endl; }
最后,显示零的数目。如果零的计数大于矩阵元素的一半,则显示矩阵是稀疏矩阵,否则显示矩阵不是稀疏矩阵。
cout<<"There are "<<count<<" zeros in the matrix"<<endl; if (count > ((r * c)/ 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl;