實施稀疏矩陣的 C++ 程式


稀疏矩陣是指其中大部分元素為 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<<"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;
}

輸出

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

在上面的程式中,使用巢狀 for 迴圈來計算矩陣中的零的數目。這透過以下程式碼段演示。

for (i = 0; i < row; ++i) {
   for (j = 0; j < col; ++j) {
      if (a[i][j] == 0)
      count++;
   }
}

在找到零的數目後,使用巢狀 for 迴圈來顯示矩陣。這在下面顯示。

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;

更新於: 24-Jun-2020

9K+ 檢視次數

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.