2D配列を使用してグラフを表現するC++プログラム
これは、2D配列を使用してグラフを表すC++プログラムです。
このアルゴリズムの時間計算量はO(v * v)です。
アルゴリズム
Begin Take the input of the number of vertex ‘v’ and edges ‘e’. Assign memory to the graph[][] matrix. Take the input of ‘e’ pairs of vertexes of the given graph in graph[][]. For each pair of connected vertex(v1, v2), store 1 in the graph[][] at the index (v1, v2) and (v2, v1). Print the matrix using PrintMatrix(). Endを使用して行列を印刷します
サンプルコード
#include<iostream>
#include<iomanip>
using namespace std;
void PrintMatrix(int **matrix, int n) {
int i, j;
cout<<"\n\n"<<setw(4)<<"";
for(i = 0; i < n; i++)
cout<<setw(3)<<"("<<i+1<<")";
cout<<"\n\n";
for(i = 0; i < n; i++) {
cout<<setw(3)<<"("<<i+1<<")";
for(j = 0; j < n; j++) {
cout<<setw(4)<<matrix[i][j];
}
cout<<"\n\n";
}
}
int main() {
int i, v, e, j, v1, v2;
cout<<"Enter the number of vertexes of the graph: ";
cin>>v;
int **graph;
graph = new int*[v];
for(i = 0; i < v; i++) {
graph[i] = new int[v];
for(j = 0; j < v; j++) graph[i][j] = 0;
}
cout<<"\nEnter the number of edges of the graph: ";
cin>>e;
for(i = 0; i < e; i++) {
cout<<"\nEnter the vertex pair for edge "<<i+1;
cout<<"\nV(1): ";
cin>>v1;
cout<<"V(2): ";
cin>>v2;
graph[v1-1][v2-1] = 1;
graph[v2-1][v1-1] = 1;
}
PrintMatrix(graph, v);
} 出力
Enter the number of vertexes of the graph: 5 Enter the number of edges of the graph: 4 Enter the vertex pair for edge 1 V(1): 2 V(2): 1 Enter the vertex pair for edge 2 V(1): 3 V(2): 2 Enter the vertex pair for edge 3 V(1): 1 V(2): 1 Enter the vertex pair for edge 4 V(1): 3 V(2): 1 (1) (2) (3) (4) (5) (1) 1 1 1 0 0 (2) 1 0 1 0 0 (3) 1 1 0 0 0 (4) 0 0 0 0 0 (5) 0 0 0 0 0
-
隣接行列を使用してグラフを表現するC++プログラム
グラフの隣接行列は、サイズV x Vの正方行列です。Vは、グラフGの頂点の数です。この行列では、各辺にV個の頂点がマークされています。グラフにiからjの頂点までのエッジがある場合、i thの隣接行列に 行とjth 列は1(または加重グラフの場合はゼロ以外の値)になります。それ以外の場合、その場所は0を保持します。 隣接行列表現の複雑さ 隣接行列表現はO(V 2 )計算中のスペースの量。グラフに最大数のエッジと最小数のエッジがある場合、どちらの場合も必要なスペースは同じになります。 入力 出力 0 1 2 3 4 5
-
DFSを使用して有向グラフの接続性をチェックするC++プログラム
グラフの接続性を確認するために、トラバーサルアルゴリズムを使用してすべてのノードをトラバースしようとします。トラバーサルの完了後、アクセスされていないノードがある場合、グラフは接続されていません。 有向グラフの場合、接続を確認するためにすべてのノードからトラバースを開始します。 1つのエッジに外向きのエッジのみがあり、内向きのエッジがない場合があるため、他の開始ノードからノードにアクセスできなくなります。 この場合、トラバーサルアルゴリズムは再帰的なDFSトラバーサルです。 入力 :グラフの隣接行列 0 1 0 0 0 0 0 1 0