কম্পিউটার

BFS ব্যবহার করে গ্রাফ একটি দ্বিপক্ষীয় কিনা তা পরীক্ষা করার জন্য C++ প্রোগ্রাম


একটি দ্বিপক্ষীয় গ্রাফ হল একটি গ্রাফ যেখানে যদি দুটি রঙ ব্যবহার করে গ্রাফ রঙ করা সম্ভব হয় যেমন; একটি সেটের শীর্ষবিন্দু একই রঙে রঙিন হয়। এটি একটি C++ প্রোগ্রাম যা একটি গ্রাফ দ্বিপক্ষীয় বা BFS ব্যবহার করছে কিনা তা পরীক্ষা করার জন্য।

অ্যালগরিদম

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. একটি নির্দেশিত গ্রাফে ইউলারিয়ান চক্র রয়েছে কিনা তা পরীক্ষা করার জন্য C++ প্রোগ্রাম

  2. একটি গ্রাফ দৃঢ়ভাবে সংযুক্ত কি না তা পরীক্ষা করার জন্য C++ প্রোগ্রাম

  3. ডিএফএস ব্যবহার করে নির্দেশিত গ্রাফের সংযোগ পরীক্ষা করার জন্য C++ প্রোগ্রাম

  4. প্রদত্ত গ্রাফটি পাইথনে দ্বিপক্ষীয় কি না তা পরীক্ষা করার জন্য প্রোগ্রাম