BFS 2-color

boolean isBipartite(List[] adj) {
  int[] color = new int[adj.length];
  Arrays.fill(color, -1);
  for (int start = 0; start < adj.length; start++) {
    if (color[start] != -1) continue;
    color[start] = 0;
    Deque q = new ArrayDeque<>();
    q.offer(start);
    while (!q.isEmpty()) {
      int u = q.poll();
      for (int v : adj[u]) {
        if (color[v] == -1) { color[v] = 1 - color[u]; q.offer(v); }
        else if (color[v] == color[u]) return false;
      }
    }
  }
  return true;
}
Advertisement

Complexity

O(V+E). Single pass.

Advertisement

Applications

Bipartite matching prerequisite. Scheduling problems. Compiler graph coloring.

Odd cycle transversal

Find min vertex set whose removal makes graph bipartite. NP-hard. FPT algorithms.