トポロジカルソートをグラフで実行できるかどうかを確認するC++プログラム
有向非巡回グラフでは、トポロジカルソートを使用して頂点を線形順序でソートできます。
トポロジカルソートは、有向非巡回グラフでのみ機能します。有向非巡回グラフ(DAG)では、複数のトポロジカルソートが存在する可能性があります。
次のC++プログラムでは、トポロジカルソートを実行して、グラフ内のサイクルの存在を確認します。
アルゴリズム
関数Topo_Sortの場合
Begin Define function Topo_Sort() Declare x to the integer datatype, vstd[] of the Boolean array and Stack as a stack. Pass them as parameter. Initialize vstd[x] = true to mark the current node as vstd. Declare an iterator i. for (i = a[x].begin(); i != a[x].end(); ++i) if (!vstd[*i]) then Call Topo_Sort(*i, vstd, Stack) function. Call push() function to insert values into stack. End.
例
#include<iostream>
#include <list>
#include <stack>
using namespace std;
class grph { // Class to represent a graph
int ver;
list<int> *a; // Pointer to an array containing adjacency listsList
void Topo_Sort(int x, bool vstd[], stack<int> &Stack); // A function used by TopologicalSort
public:
grph(int ver); // Constructor of grpf
void Insert_Edge(int x, int y); // to insert an edge to graph
void Topol_Sort(); // prints a Topological Sort of the complete graph
};
grph::grph(int ver) {
this->ver = ver;
a = new list<int>[ver];
}
void grph::Insert_Edge(int x, int y) {
a[x].push_back(y); // Add y to x’s list.
}
// A recursive function used by Topol_Sort
void grph::Topo_Sort(int x, bool vstd[], stack<int> &Stack) {
vstd[x] = true; // Mark the current node as vstd.
list<int>::iterator i;
for (i = a[x].begin(); i != a[x].end(); ++i)
if (!vstd[*i])
Topo_Sort(*i, vstd, Stack);
// Push current vertex to stack which stores result
Stack.push(x);
}
void grph::Topol_Sort() {
stack<int> Stack;
// Mark all the vertices as not vstd
bool *vstd = new bool[ver];
for (int i = 0; i < ver; i++)
vstd[i] = false;
for (int i = 0; i < ver; i++)
if (vstd[i] == false)
Topo_Sort(i, vstd, Stack);
while (Stack.empty() == false) {
cout << Stack.top() << " ";
Stack.pop();
}
}
int main() {
grph g(6); // Create a graph given in the above diagram
g.Insert_Edge(5, 2);
g.Insert_Edge(5, 0);
g.Insert_Edge(4, 0);
g.Insert_Edge(4, 1);
g.Insert_Edge(2, 3);
g.Insert_Edge(3, 1);
cout << "Topological Sort of the graph is: \n";
g.Topol_Sort();
return 0;
} 出力
Topological Sort of the graph is: 5 4 2 3 1 0
-
有向グラフにオイラー閉路が含まれているかどうかを確認するC++プログラム
オイラーサイクル/回路はパスです。これにより、すべてのエッジを1回だけ訪問できます。同じ頂点を複数回使用できます。オイラー回路は、特殊なタイプのオイラーパスです。オイラーパスの開始頂点がそのパスの終了頂点にも接続されている場合、それはオイラー回路と呼ばれます。 グラフがオイラーであるかどうかを確認するには、2つの条件を確認する必要があります- グラフを接続する必要があります。 各頂点の次数と次数は同じである必要があります。 入力 −グラフの隣接行列。 0 1 0 0 0 0 0 1 0 0 0 0 0
-
グラフが強く接続されているかどうかをチェックするC++プログラム
有向グラフでは、1つのコンポーネントの頂点の各ペアの間にパスがある場合、コンポーネントは強く接続されていると言われます。 このアルゴリズムを解決するには、まず、DFSアルゴリズムを使用して各頂点の終了時間を取得し、次に転置されたグラフの終了時間を検索します。次に、頂点をトポロジカルソートの降順で並べ替えます。 入力 :グラフの隣接行列。 0 0 1 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 出力 :以下は、与え