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

2色アルゴリズムを使用してグラフが2部グラフであるかどうかを確認するC++プログラム


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

関数と擬似コード

Begin
   1. Develop function isSafe() to check if the current color assignment
      is safe for vertex v, i.e. checks whether the edge exists or not.
      If it exists, then next check whether the color to be filled in
      the new vertex is already used by its adjacent vertices.
   2. function graphColoringtil(bool g[V][V], int k, int col[], int v) :
      g[V][V] = It is a 2D array where V is the number of vertices in graph
      k = maximum number of colors that can be used.
      col[] = an color array that should have numbers from 1 to m.
      if v == V
      return true
      For c = 1 to k
      if (isSafe(v, g, col, c))
         col[v] = c
         if (graphColoringtil (g, k, col, v+1) == true)
            return true
         col[v] = 0
      return false
   3.function graphColoring(bool g[V][V], int k):
   for i = 0 to V-1
      color[i] = 0
      if (graphColoringtil(g, k, color, 0) == false)
   return false
return true

#include <iostream>
#include <cstdio>
#define V 4
using namespace std;
bool isSafe (int v, bool g[V][V], int col[], int C) //to solve m coloring //problem
{
   for (int i = 0; i < V; i++)
      if (g[v][i] && C == col[i])
      return false;
   return true;
}
bool graphColoringtil(bool g[V][V], int k, int col[], int v)
{
   if (v == V) //If all vertices are assigned a color then
   return true;
   for (int c = 1; c <= k; c++) //Consider this vertex v and try different colors
   {
      if (isSafe(v, g, col, c)) //Check if assignment of color c to v is fine
      {
         col[v] = c;
         if (graphColoringtil (g, k, col, v+1) == true) //recur to assign colors to rest of the vertices
         return true;
         col[v] = 0; //If assigning color c doesn't lead to a solution then remove it
      }
   }
   return false;
}

出力

The graph is Bipartite

  1. 無向グラフにオイラー閉路が含まれているかどうかを確認するC++プログラム

    オイラー回路について知るために、オイラーパスについての考えがあります。オイラーパスはパスです。これにより、すべてのノードに1回だけアクセスできます。同じエッジを複数回使用できます。オイラー回路は、特殊なタイプのオイラーパスです。オイラーパスの開始頂点がそのパスの終了頂点にも接続されている場合。 回路を検出するには、次の条件に従う必要があります。 グラフを接続する必要があります。 無向グラフの頂点の次数が奇数でない場合、それはオイラー回路です。 入力 出力 グラフにはオイラー回路があります。 アルゴリズム traverse(u、visited) 入力開始ノードuと訪問済みノード

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