スパース配列を実装するC++プログラム
スパース行列は、要素の大部分が0である行列です。この例を次に示します。
以下に示す行列には、5つのゼロが含まれています。ゼロの数は行列の要素の半分以上であるため、スパース行列です。
0 0 9 5 0 8 7 0 0
アルゴリズム
Begin
Declare a 2D array a[10][10] to the integer datatype.
Initialize some values of array.
Declare i, j, count to the integer datatype.
Initialize count = 0.
Declare row, col to the integer datatype.
Initialize row = 3, col = 3.
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j)
if (a[i][j] == 0)
count++.
Print “The matrix is:” .
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
Print the values of array.
Print “The number of zeros in the matrix are”.
if (count > ((row * col)/ 2)) then
Print "This is a sparse matrix".
else
Print "This is not a sparse matrix".
End. 例
#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
-
隣接行列を実装するためのC++プログラム
グラフの隣接行列は、サイズV x Vの正方行列です。VはグラフGの頂点の数です。この行列では、各辺にV個の頂点がマークされています。グラフにiからjの頂点までのエッジがある場合、i thの隣接行列に 行とjth 列は1(または加重グラフの場合はゼロ以外の値)になります。それ以外の場合、その場所は0を保持します。 隣接行列表現の複雑さ: 隣接行列表現は、計算中にO(V2)のスペースを取ります。グラフに最大数のエッジと最小数のエッジがある場合、どちらの場合も必要なスペースは同じになります。 入力: 出力: 0 1 2 3 4
-
それがスパース行列であるかどうかをチェックする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} }; &n