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

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


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

アルゴリズム

Begin
   Function Bipartite():
   1) Assign a color to the source vertex
   2) Color all the neighbors with another color except first one color.
   3) Color all neighbor’s neighbor with First color.
   4) Like this way, assign color to all vertices such that it satisfies all the constraints of k way coloring problem where k = 2.
   5) While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices i.e.; graph is not Bipartite
End

#include <iostream>
#include <queue>
#define V 5
using namespace std;
bool Bipartite(int G[][V], int s) {
   int colorA[V];
   for (int i = 0; i < V; ++i)
   colorA[i] = -1;
   colorA[s] = 1; //Assign a color to the source vertex
   queue <int> q; //Create a queue of vertex numbers and enqueue source vertex for BFS traversal
   q.push(s);
   while (!q.empty()) {
      int w = q.front(); //dequeue a vertex
      q.pop();
      for (int v = 0; v < V; ++v) //Find all non-colored adjacent vertices {
         if (G[w][v] && colorA[v] == -1) //An edge from w to v exists and destination v is not colored {
            colorA[v] = 1 - colorA[w]; //Assign alternate color to this adjacent v of w
            q.push(v);
         } else if (G[w][v] && colorA[v] == colorA[w]) //An edge from w to v exists and destination
            //v is colored with same color as u
            return false;
      }
   }
   return true; //if all adjacent vertices can be colored with alternate color
}
int main() {
   int G[][V] = {{ 0, 1, 0, 0},
                { 1, 0, 0, 0},
                { 0, 0, 0, 1},
                { 1, 0, 1, 0}};
   if (Bipartite(G, 0))
      cout << "The Graph is Bipartite"<<endl;
   else
      cout << "The Graph is Not Bipartite"<<endl;
   return 0;
}

出力

The Graph is Bipartite

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

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

  2. 与えられたグラフがPythonで2部グラフであるかどうかをチェックするプログラム

    無向グラフが1つあるとすると、グラフが2部グラフであるかどうかを確認する必要があります。グラフのすべてのエッジ{u、v}がAに1つのノードuを持ち、Bに別のノードvを持つように、グラフのノードを2つのセットAとBに分割できる場合、グラフは2部グラフであることがわかります。 したがって、入力が次のような場合 次に、出力はTrueになり、[0,4]はセットAにあり、[1,2,3]はセットBにあり、すべてのエッジはAからAまたはBからBではなく、AからBまたはBからAになります。 。 これを解決するために、次の手順に従います- 関数dfs()を定義します。これはソースを取ります