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

DFSを使用してグラフが2部グラフであるかどうかを確認するC++プログラム


2部グラフは、グラフの彩色が2つの色を使用して可能である場合にグラフです。セット内の頂点は同じ色で色付けされます。これは、グラフが2部グラフであるかどうかをDFSを使用してチェックするC++プログラムです。

アルゴリズム

Begin
   1. An array color[] is used to stores 0 or 1 for every node which denotes opposite colors.
   2. Call function DFS from any node.
   3. If the node w has not been visited previously, then assign !
      color[v] to color[w] and call DFS again to visit nodes connected to w.
   4. If at any instance, color[u] is equal to !color[v], then the node is bipartite.
   5. Modify the DFS function
End

#include<iostream>
#include <bits/stdc++.h>
using namespace std;
void addEd(vector<int> adj[], int w, int v) //adding edge to the graph {
   adj[w].push_back(v); //add v to w’s list
   adj[v].push_back(w); //add w to v’s list
}
bool Bipartite(vector<int> adj[], int v,
vector<bool>& visited, vector<int>& color) {
   for (int w : adj[v]) {
      // if vertex w is not explored before
      if (visited[w] == false) {
         // mark present vertex as visited
         visited[w] = true;
         color[w] = !color[v]; //mark color opposite to its parents
         if (!Bipartite(adj, w, visited, color))
            return false;
      }
      // if two adjacent are colored with same color then the graph is not bipartite
         else if (color[w] == color[v])
            return false;
   }
   return true;
}
int main() {
   int M = 6;
   vector<int> adj[M + 1];
   // to keep a check on whether
   // a node is discovered or not
   vector<bool> visited(M + 1);
   vector<int> color(M + 1); //to color the vertices of the graph with 2 color
   addEd(adj, 3,2);
   addEd(adj, 1,4 );
   addEd(adj, 2, 1);
   addEd(adj, 5,3);
   addEd(adj, 6,2);
   addEd(adj, 3,1);
   visited[1] = true;
   color[1] = 0;
   if (Bipartite(adj, 1, visited, color)) {
      cout << "Graph is Bipartite";
   } else {
      cout << "Graph is not Bipartite";
   }
   return 0;
}

出力

Graph is not Bipartite

  1. グラフが強く接続されているかどうかをチェックする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 出力 :以下は、与え

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

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