@@ -79,37 +79,14 @@ namespace ariel{
79
79
// sort of BFS on the graph
80
80
for (size_t ind = 0 ; ind < graph.getSize (); ++ind) {
81
81
if (color[ind] == " WHITE" ) {
82
- queue<size_t > queue;
83
- color[ind] = " BLUE" ;
84
- setA.push_back (ind); // Add the starting vertex to setA
85
- queue.push (ind); // push starting vertex to queue
86
-
87
- while (!queue.empty ()) {
88
- size_t vertice = queue.front ();
89
- queue.pop ();
90
-
91
- for (size_t neighbor = 0 ; neighbor < graph.getSize (); ++neighbor) {
92
- if (graph.getWeight (vertice, neighbor) != 0 ) {
93
- if (color[neighbor] == " WHITE" ) {
94
- color[neighbor] = (color[vertice] == " BLUE" ) ? " RED" : " BLUE" ;
95
- queue.push (neighbor);
96
-
97
- // Add the vertex to its set based on its color
98
- if (color[neighbor] == " RED" ) {
99
- setB.push_back (neighbor);
100
- } else {
101
- setA.push_back (neighbor);
102
- }
103
- } else if (color[neighbor] == color[vertice]) {
104
- // If adjacent vertices have the same color, the graph is not bipartite
105
- return " 0" ;
106
- }
107
- }
108
- }
82
+ if (!bfsBipartite (graph, color, setA, setB, ind)){
83
+ return " 0" ; // The graph is not bipartite
109
84
}
110
85
}
111
86
}
112
87
88
+ // if we reached here, the graph is bipartite
89
+
113
90
// Build the result string
114
91
result += " The graph is bipartite: A={" ;
115
92
for (size_t ind = 0 ; ind < setA.size (); ++ind) {
@@ -215,6 +192,38 @@ namespace ariel{
215
192
return false ; // No cycle found
216
193
}
217
194
195
+ bool Algorithms::bfsBipartite (Graph& graph, vector<string>& color, vector<size_t >& setA, vector<size_t >& setB, size_t start) {
196
+ queue<size_t > queue;
197
+ color[start] = " BLUE" ;
198
+ setA.push_back (start); // Add the starting vertex to setA
199
+ queue.push (start); // push starting vertex to queue
200
+
201
+ while (!queue.empty ()) {
202
+ size_t vertice = queue.front ();
203
+ queue.pop ();
204
+
205
+ for (size_t neighbor = 0 ; neighbor < graph.getSize (); ++neighbor) {
206
+ if (graph.getWeight (vertice, neighbor) != 0 ) {
207
+ if (color[neighbor] == " WHITE" ) {
208
+ color[neighbor] = (color[vertice] == " BLUE" ) ? " RED" : " BLUE" ;
209
+ queue.push (neighbor);
210
+
211
+ // Add the vertex to its set based on its color
212
+ if (color[neighbor] == " RED" ) {
213
+ setB.push_back (neighbor);
214
+ } else {
215
+ setA.push_back (neighbor);
216
+ }
217
+ } else if (color[neighbor] == color[vertice]) {
218
+ // If adjacent vertices have the same color, the graph is not bipartite
219
+ return false ;
220
+ }
221
+ }
222
+ }
223
+ }
224
+ return true ; // The graph is bipartite
225
+ }
226
+
218
227
string Algorithms::isContainsCycle (Graph graph) {
219
228
vector<bool > visited (graph.getSize (), false );
220
229
vector<size_t > parent (graph.getSize (), INT32_MAX);
0 commit comments