package com.dsprep.graph;
import java.util.ArrayList;
import java.util.Iterator;
public class BipartiteGraphDFS {
public BipartiteGraphDFS() {
}
void addEdge(ArrayList<ArrayList<Integer>> adj, int v, int u){
adj.get(v).add(u);
adj.get(u).add(v);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<10;i++){
adj.add(new ArrayList<>());
}
BipartiteGraphDFS g = new BipartiteGraphDFS();
g.addEdge(adj,1, 2);
g.addEdge(adj,2, 3);
g.addEdge(adj,2, 8);
g.addEdge(adj,3, 4);
g.addEdge(adj,4, 6);
g.addEdge(adj,5, 7);
g.addEdge(adj,5, 9);
g.addEdge(adj,8, 9);
// g.addEdge(adj,7,9);
boolean[] visited = new boolean[10];
boolean[] color = new boolean[10];
if(g.DFS(1,adj,visited,color)){
System.out.println("Bipartite");
}else{
System.out.println("not bipartite");
}
}
boolean DFS(int v,ArrayList<ArrayList<Integer>> adj,boolean[] visited, boolean[] color){
visited[v]=true;
System.out.println(v);
ArrayList<Integer> list = adj.get(v);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
Integer i = iterator.next();
if(!visited[i]){
color[i] = !color[v];
if(!DFS(i,adj,visited,color)){
return false;
}
}else if(color[i]==color[v]){
return false;
}
}
return true;
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class BipartiteGraphDFS {
public BipartiteGraphDFS() {
}
void addEdge(ArrayList<ArrayList<Integer>> adj, int v, int u){
adj.get(v).add(u);
adj.get(u).add(v);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<10;i++){
adj.add(new ArrayList<>());
}
BipartiteGraphDFS g = new BipartiteGraphDFS();
g.addEdge(adj,1, 2);
g.addEdge(adj,2, 3);
g.addEdge(adj,2, 8);
g.addEdge(adj,3, 4);
g.addEdge(adj,4, 6);
g.addEdge(adj,5, 7);
g.addEdge(adj,5, 9);
g.addEdge(adj,8, 9);
// g.addEdge(adj,7,9);
boolean[] visited = new boolean[10];
boolean[] color = new boolean[10];
if(g.DFS(1,adj,visited,color)){
System.out.println("Bipartite");
}else{
System.out.println("not bipartite");
}
}
boolean DFS(int v,ArrayList<ArrayList<Integer>> adj,boolean[] visited, boolean[] color){
visited[v]=true;
System.out.println(v);
ArrayList<Integer> list = adj.get(v);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
Integer i = iterator.next();
if(!visited[i]){
color[i] = !color[v];
if(!DFS(i,adj,visited,color)){
return false;
}
}else if(color[i]==color[v]){
return false;
}
}
return true;
}
}
No comments:
Post a Comment