forked from striver79/StriversGraphSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bipartiteGraphJavaDfs
71 lines (56 loc) · 1.39 KB
/
bipartiteGraphJavaDfs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.*;
class Main
{
boolean dfsCheck(ArrayList<ArrayList<Integer>> adj, int node, int color[]) {
for(Integer it: adj.get(node)) {
if(color[it] == -1) {
color[it] = 1 - color[node];
if(!dfsCheck(adj, it, color))
return false;
}
else if(color[it] == color[node]) {
return false;
}
}
return true;
}
boolean checkBipartite(ArrayList<ArrayList<Integer>> adj, int n)
{
int color[] = new int[n];
for(int i = 0;i<n;i++) {
color[i] = -1;
}
for(int i = 0;i<n;i++) {
if(color[i] == -1) {
if(!dfsCheck(adj, i, color)) {
return false;
}
}
}
return true;
}
public static void main(String args[])
{
int n = 7;
ArrayList<ArrayList<Integer> > adj = new ArrayList<ArrayList<Integer> >();
for (int i = 0; i < n; i++)
adj.add(new ArrayList<Integer>());
adj.get(0).add(1);
adj.get(1).add(0);
adj.get(1).add(2);
adj.get(2).add(1);
adj.get(2).add(3);
adj.get(3).add(2);
adj.get(4).add(3);
adj.get(3).add(4);
adj.get(4).add(5);
adj.get(5).add(4);
adj.get(4).add(6);
adj.get(6).add(4);
adj.get(1).add(6);
adj.get(6).add(1);
Main obj = new Main();
if(obj.checkBipartite(adj, n) == true) System.out.println("Yes Bipartite");
else System.out.println("Not Bipartite");
}
}