1. class Solution {
  2. public boolean isBipartite(int V, int[][] edges) {
  3.  
  4. // create a adjacency list
  5. ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
  6. for(int i=0; i<V; i++)
  7. {
  8. adj.add(new ArrayList<Integer>());
  9. }
  10.  
  11. // fill the adjacency list
  12. for(int[] edge : edges)
  13. {
  14. int u = edge[0];
  15. int v = edge[1];
  16.  
  17. // undirected graph
  18. adj.get(u).add(v);
  19. adj.get(v).add(u);
  20. }
  21.  
  22. int[] color = new int[V];
  23. Arrays.fill(color, -1);
  24.  
  25. for(int i=0; i<V; i++)
  26. {
  27. // only start BFS if node is uncolored
  28. if (color[i] == -1)
  29. {
  30. if(bfs(adj, color, i) == false)
  31. return false;
  32. }
  33. }
  34. return true;
  35. }
  36.  
  37. public boolean bfs(ArrayList<ArrayList<Integer>> adj, int[] color, int node)
  38. {
  39. Queue<Integer> q = new LinkedList<>();
  40. q.add(node);
  41. color[node] = 0;
  42.  
  43. while(!q.isEmpty())
  44. {
  45. int u = q.poll();
  46.  
  47. for(int v : adj.get(u))
  48. {
  49. // neighbour node and current node has same color, so not a bipartite graph
  50. if(color[v] == color[u])
  51. return false;
  52.  
  53. // assign opposite color
  54. else if(color[v] == -1)
  55. {
  56. // assigning opposite color
  57. color[v] = 1 - color[u];
  58. q.add(v);
  59. }
  60. }
  61. }
  62. return true;
  63. }
  64. }