Skip to content

Commit db1cdba

Browse files
authored
Create 27 - Possible Bipartition.cpp
1 parent 38370c1 commit db1cdba

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

27 - Possible Bipartition.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
class Solution {
2+
public:
3+
bool isBipertite(vector < vector <int> > &graph, int src, vector <int> &visited){
4+
// Create a color array to store colors
5+
// assigned to all veritces. Vertex
6+
// number is used as index in this array.
7+
// The value '-1' of colorArr[i]
8+
// is used to indicate that no color
9+
// is assigned to vertex 'i'. The value 1
10+
// is used to indicate first color
11+
// is assigned and value 0 indicates
12+
// second color is assigned.
13+
14+
vector <int> color(graph.size());
15+
16+
for(int i = 0; i<color.size(); i++){
17+
color[i] = -1;
18+
}
19+
// Assign first color to source
20+
color[src] = 1;
21+
22+
queue <int> q;
23+
q.push(src);
24+
25+
while(!q.empty()){
26+
27+
int temp = q.front();
28+
visited[temp] = 1;
29+
q.pop();
30+
// Return false if there is a self-loop , not possible in this problem
31+
if(graph[temp][temp] == 1){
32+
return false;
33+
}
34+
// Find all non-colored adjacent vertices
35+
for(int i = 0; i<graph.size(); i++){
36+
// An edge from u to v exists and destination v is not colored
37+
if(graph[temp][i] && color[i] == -1){
38+
// Assign alternate color to this adjacent v of u
39+
color[i] = 1 - color[temp];
40+
q.push(i);
41+
}
42+
// An edge from u to v exists and destination v is colored with same color as u
43+
else if(graph[temp][i] && color[i] == color[temp]){
44+
return false;
45+
}
46+
}
47+
}
48+
49+
return true;
50+
}
51+
52+
53+
bool possibleBipartition(int N, vector<vector<int>>& dislikes) {
54+
vector < vector <int> > graph(N+1, vector <int> (N+1, 0));
55+
for(int i = 0; i < dislikes.size(); i++){
56+
int u = dislikes[i][0];
57+
int v = dislikes[i][1];
58+
graph[u][v] = 1;
59+
graph[v][u] = 1;
60+
}
61+
int res = 0;
62+
int src = 0;
63+
vector <int> visited(N+1,0);
64+
visited[0] = 1;
65+
res = isBipertite(graph, 1, visited);
66+
if(res == 1){
67+
for(int i = 0; i<=N; i++){
68+
if(visited[i] == 0){
69+
res = isBipertite(graph, i, visited);
70+
}
71+
if(res == 0){
72+
return 0;
73+
}
74+
}
75+
}
76+
return res;
77+
}
78+
};

0 commit comments

Comments
 (0)