グラフの推移閉包を見つけるためのC++プログラム
有向グラフが指定されている場合は、指定されたグラフのすべての頂点ペア(i、j)について、頂点jが別の頂点iから到達可能かどうかを判断します。到達可能とは、頂点iからjへのパスがあることを意味します。この到達可能性マトリックスは、グラフの推移閉包と呼ばれます。 Warshallアルゴリズムは、特定のグラフGの推移閉包を見つけるために一般的に使用されます。これは、このアルゴリズムを実装するためのC++プログラムです。
アルゴリズム
Begin 1. Take maximum number of nodes as input. 2. For Label the nodes as a, b, c….. 3. To check if there any edge present between the nodes make a for loop: // ASCII code of a is 97 for i = 97 to (97 + n_nodes)-1 for j = 97 to (97 + n_nodes)-1 If edge is present do, adj[i - 97][j - 97] = 1 else adj[i - 97][j - 97] = 0 End loop End loop. 4. To print the transitive closure of graph: for i = 0 to n_nodes-1 c = 97 + i End loop. for i = 0 to n_nodes-1 c = 97 + i for j = 0 to n_nodes-1 Print adj[I][j] End loop End loop End
例
#include<iostream>
using namespace std;
const int n_nodes = 20;
int main()
{
int n_nodes, k, n;
char i, j, res, c;
int adj[10][10], path[10][10];
cout << "\n\tMaximum number of nodes in the graph :";
cin >> n;
n_nodes = n;
cout << "\nEnter 'y' for 'YES' and 'n' for 'NO' \n";
for (i = 97; i < 97 + n_nodes; i++)
for (j = 97; j < 97 + n_nodes; j++)
{
cout << "\n\tIs there an edge from " << i << " to "
<< j << " ? ";
cin >> res;
if (res == 'y')
adj[i - 97][j - 97] = 1;
else
adj[i - 97][j - 97] = 0;
}
cout << "\n\nTransitive Closure of the Graph:\n";
cout << "\n\t\t\t ";
for (i = 0; i < n_nodes; i++)
{
c = 97 + i;
cout << c << " ";
}
cout << "\n\n";
for (int i = 0; i < n_nodes; i++)
{
c = 97 + i;
cout << "\t\t\t" << c << " ";
for (int j = 0; j < n_nodes; j++)
cout << adj[i][j] << " ";
cout << "\n";
}
return 0;
} 出力
Maximum number of nodes in the graph :4 Enter 'y' for 'YES' and 'n' for 'NO' Is there an edge from a to a ? y Is there an edge from a to b ?y Is there an edge from a to c ? n Is there an edge from a to d ? n Is there an edge from b to a ? y Is there an edge from b to b ? n Is there an edge from b to c ? y Is there an edge from b to d ? n Is there an edge from c to a ? y Is there an edge from c to b ? n Is there an edge from c to c ? n Is there an edge from c to d ? n Is there an edge from d to a ? y Is there an edge from d to b ? n Is there an edge from d to c ? y Is there an edge from d to d ? n Transitive Closure of the Graph: a b c d a 1 1 0 0 b 1 0 1 0 c 1 0 0 0 d 1 0 1 0
-
グラフの推移閉包(Transitive Closure)とは?ワーシャル法によるアルゴリズムとC++実装を解説
グラフにおける推移閉包(Transitive Closure)とは、ある頂点 u から別の頂点 v へ「到達できるかどうか」を示す到達可能性行列のことです。1つのグラフが与えられたとき、すべての頂点ペア (u, v) について、u から v が到達可能かどうかを求めます。 最終的に得られる行列はブール型(0 と 1 のみ)で構成されます。頂点 u から頂点 v に対応する要素が 1 である場合、「u から v へ至る経路が少なくとも 1 本存在する」ことを意味します。逆に 0 であれば、いかなる経路を通っても u から v には到達できないことを表します。 この手法は、隣接行列に対して動
-
グラフ内のスーパー頂点を見つけるC++プログラムの解説
問題の概要n個の頂点を持つグラフが与えられていると仮定しましょう。頂点には1からnまでの番号が付けられており、配列「edges」に含まれる辺によって互いに接続されています。さらに、各頂点は1からnの範囲の数値である「x」という値を持ち、その値は配列「values」で与えられます。このとき、グラフの中から「スーパー頂点(super vertex)」と呼ばれる特別な頂点を見つけ出す必要があります。頂点iがスーパー頂点であるとは、頂点1から頂点iへの最短経路上に、i番目の頂点と同じ「x」の値を持つ頂点が存在しないことを意味します。この条件を満たすすべての頂点を出力してください。たとえば、入力が n