實施稀疏矩陣的 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;
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP