C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

有向非巡回グラフのトポロジカルソートを実行するためにDFSを適用するC++プログラム


DAG(有向非巡回グラフ)のトポロジカルソートは、すべての有向エッジuvに対して、頂点uが順序付けでvの前に来るような頂点の線形順序付けです。グラフがDAGでない場合、グラフのトポロジカルソートはできません。

関数と擬似コード

Begin
   function topologicalSort():
   a) Mark the current node as visited.
   b) Recur for all the vertices adjacent to this vertex.
   c) Push current vertex to stack which stores result.
End
Begin
   function topoSort() which uses recursive topological sort() function:
   a) Mark all the vertices which are not visited.
   b) Call the function topologicalSort().
   c) Print the content.
End

#include<iostream>
#include <list>
#include <stack>
using namespace std;
class G {
   int n;
   list<int> *adj;
   //declaration of functions
   void topologicalSort(int v, bool visited[], stack<int> &Stack);
   public:
   G(int n); //constructor
   void addEd(int v, int w);
   void topoSort();
};
G::G(int n) {
   this->n = n;
   adj = new list<int> [n];
}
void G::addEd(int v, int w) // add the edges to the graph. {
   adj[v].push_back(w); //add w to v’s list
}
void G::topologicalSort(int v, bool visited[], stack<int> &Stack) {
   visited[v] = true; //mark current node as visited
   list<int>::iterator i;
   //Recur for all the vertices adjacent to this vertex.
   for (i = adj[v].begin(); i != adj[v].end(); ++i)
      if (!visited[*i])
         topologicalSort(*i, visited, Stack);
         Stack.push(v);
}
void G::topoSort() {
   stack<int> Stack;
   bool *visited = new bool[n];
   //Mark all the vertices which are not visited.
   for (int i = 0; i < n; i++)
      visited[i] = false;
      for (int i = 0; i < n; i++)
         if (visited[i] == false)
            //Call the function topologicalSort().
            topologicalSort(i, visited, Stack);
         while (Stack.empty() == false) {
            cout << Stack.top() << " "; //print the element
            Stack.pop();
         }
}
int main() {
   G g(6);
   g.addEd(4, 2);
   g.addEd(5, 1);
   g.addEd(4, 0);
   g.addEd(3, 1);
   g.addEd(1, 3);
   g.addEd(3, 2);
   cout << " Topological Sort of the given graph \n";
   g.topoSort();
   return 0;
}

出力

Topological Sort of the given graph
5 4 1 3 2 0

  1. BFSを使用して有向グラフの接続性をチェックするC++プログラム

    グラフの接続性を確認するために、トラバーサルアルゴリズムを使用してすべてのノードをトラバースしようとします。トラバーサルの完了後、アクセスされていないノードがある場合、グラフは接続されていません。 有向グラフの場合、接続を確認するためにすべてのノードからトラバースを開始します。 1つのエッジに外側のエッジのみがあり、内側のエッジがない場合があるため、ノードは他の開始ノードからアクセスされません。 この場合、トラバーサルアルゴリズムは再帰的なBFSトラバーサルです。 入力 −グラフの隣接行列 0 1 0 0 0 0 0 1 0 0

  2. DFSを使用して有向グラフの接続性をチェックするC++プログラム

    グラフの接続性を確認するために、トラバーサルアルゴリズムを使用してすべてのノードをトラバースしようとします。トラバーサルの完了後、アクセスされていないノードがある場合、グラフは接続されていません。 有向グラフの場合、接続を確認するためにすべてのノードからトラバースを開始します。 1つのエッジに外向きのエッジのみがあり、内向きのエッジがない場合があるため、他の開始ノードからノードにアクセスできなくなります。 この場合、トラバーサルアルゴリズムは再帰的なDFSトラバーサルです。 入力 :グラフの隣接行列 0 1 0 0 0 0 0 1 0