Skip to content

Commit dcbc451

Browse files
author
Skm2000
committed
Added Course Schedule
1 parent 99327d8 commit dcbc451

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Solutions/Course_Schedule.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
class Solution {
5+
private:
6+
// using bfs
7+
bool isBipartite(vector<vector<int>>&adj,int N,int node,vector<int>&color){
8+
queue<int>q;
9+
q.push(node);
10+
color[node]=1;
11+
while(!q.empty()){
12+
int curr=q.front();
13+
q.pop();
14+
for(int ele:adj[curr]){
15+
if(color[ele] == color[curr]){ //bipartite cannot have two adjacent nodes of same color
16+
return false;
17+
}
18+
if(color[ele]==-1){
19+
color[ele]=1-color[curr];
20+
q.push(ele);
21+
}
22+
}
23+
}
24+
return true;
25+
}
26+
public:
27+
bool possibleBipartition(int N, vector<vector<int>>& dislikes) {
28+
//Making adjacency list
29+
vector<vector<int>>adj(N+1);
30+
for(int i=0;i<dislikes.size();i++){
31+
adj[dislikes[i][0]].push_back(dislikes[i][1]);
32+
adj[dislikes[i][1]].push_back(dislikes[i][0]);
33+
}
34+
// a color array
35+
// -1:not visited, 1: denotes first color set, 0: denotes second color set
36+
vector<int>color(N+1,-1);
37+
for(int i=0;i<N;i++){
38+
if(color[i]==-1){
39+
if(!isBipartite(adj,N,i,color))
40+
return false;
41+
}
42+
}
43+
return true;
44+
}
45+
};

0 commit comments

Comments
 (0)