1
1
#include < bits/stdc++.h>
2
2
using namespace std ;
3
3
4
+ // The solution basically uses the concept of graph coloring
5
+ // 0: node has not been visited
6
+ // 2: node is in processing mode
7
+ // 1: node has allready been processed
8
+
4
9
class Solution {
5
10
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
- }
11
+ bool isCyclic (vector<vector<int >>&adj,vector<int >&visited,int current){
12
+ if (visited[current]==2 )
13
+ return true ;
14
+ visited[current]=2 ;
15
+ for (int i=0 ;i<adj[current].size ();i++){
16
+ if (visited[adj[current][i]]!=1 ){
17
+ if (isCyclic (adj,visited,adj[current][i]))
18
+ return true ;
22
19
}
23
20
}
24
- return true ;
21
+ visited[current]=1 ;
22
+ return false ;
25
23
}
26
24
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 ]);
25
+ bool canFinish (int numCourses, vector<vector<int >>& prerequisites) {
26
+ vector<vector<int >>adj (numCourses);
27
+ for (int i=0 ;i<prerequisites.size ();i++){
28
+ adj[prerequisites[i][0 ]].push_back (prerequisites[i][1 ]);
33
29
}
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))
30
+ vector<int >visited (numCourses,0 );
31
+ for (int i=0 ;i<numCourses;i++){
32
+ if (visited[i]==0 ){
33
+ if (isCyclic (adj,visited,i)){
40
34
return false ;
35
+ }
41
36
}
42
37
}
43
38
return true ;
44
39
}
45
- };
40
+ };
0 commit comments