Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. public class CheckBipartiteGraph {
  2.  
  3. enum Color{
  4. WHITE, RED, GREEN
  5. }
  6.  
  7. public boolean isBipartite(int [][] graph){
  8.  
  9. //check if graph is empty
  10. if(graph.length==0)
  11. return true;
  12.  
  13. int vertices = graph.length;
  14.  
  15. //initialize colors for all vertices
  16. Color colors[] = new Color[vertices];
  17. //color all the vertices with white color
  18. for (int i = 0; i <colors.length ; i++) {
  19. colors[i] = Color.WHITE;
  20. }
  21.  
  22. //start coloring vertices , this code will handle the disconnected graph as well
  23. //color the first vertex with RED
  24. for (int i = 0; i <vertices; i++) {
  25. if(colors[i]==Color.WHITE) {
  26. boolean result = isBipartiteUtil(i, vertices, colors, graph);
  27. if(result==false)
  28. return false;
  29. }
  30. }
  31. return true;
  32. }
  33.  
  34. private boolean isBipartiteUtil(int u, int vertices, Color [] colors, int [][]graph){
  35.  
  36. //if is it first vertex, mark it RED
  37. if(u==0)
  38. colors[u]= Color.RED;
  39.  
  40. //travel all adjacent vertices
  41. for (int v = 0; v <vertices ; v++) {
  42. //if u-v exist and v is color with white
  43. if(graph[u][v]==1 && colors[v]==Color.WHITE){
  44. //color is with the alternate color of vertex v
  45. if(colors[u]==Color.RED) {
  46. //if u is in red, make vertex v in green
  47. colors[v] = Color.GREEN;
  48. }
  49. else if (colors[u]==Color.GREEN) {
  50. //if u is in green, make vertex v in red
  51. colors[v] = Color.RED;
  52. }
  53.  
  54. //make recursive call
  55.  
  56. return isBipartiteUtil(v, vertices, colors, graph);
  57. }else if(graph[u][v]==1 && colors[u]==colors[v]){
  58. return false;
  59. }
  60. }
  61. // if here means graph is successfully colored in 2 color, red and green
  62. //graph is bipartite
  63. return true;
  64. }
  65.  
  66.  
  67. public static void main(String[] args) {
  68. CheckBipartiteGraph c = new CheckBipartiteGraph();
  69. int [][] graph = { {0, 1, 1, 1},
  70. {1, 0, 0, 1},
  71. {0, 0, 0, 1},
  72. {1, 1, 1, 0}
  73. };
  74. boolean result = c.isBipartite(graph);
  75. System.out.println("Graph is Bipartite: " + result);
  76. System.out.println("--------------------------");
  77. int [][] graph1 = { {0, 1, 1, 0},
  78. {1, 0, 0, 1},
  79. {1, 0, 0, 1},
  80. {0, 1, 1, 0}
  81. };
  82. result = c.isBipartite(graph1);
  83. System.out.println("Graph is Bipartite: " + result);
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement