AlgoFrames

Bipartite check by 2-coloring

A graph is bipartite when its vertices split into two groups with every edge crossing between them. Two-colour it with BFS and watch for a conflict.

Before you start: Cycle detection in undirected and directed graphs.

The idea

Each line joins two people who cannot share a team. Can everyone be placed on one of two teams?

A graph that allows this is called bipartite. Scheduling, matching and conflict problems often reduce to this question.

Intuition

Here it works. Group A and group B are filled in, and every edge joins an A node to a B node.

A triangle fails. After A and B take two corners, the third (?) touches both colors and has no color left.

Complexity

BFS checks each edge a constant number of times: O(V + E). The rescan curve rechecks every edge for every node, V × E.

Trying every way to split the nodes into two groups would take 2 to the power V. BFS rules out all of them at once.

Space is O(V). The color table and the queue hold at most one entry per node.

Pitfalls

One search only reaches one connected part. Start again from every node that still has no color.

A conflict is often an edge that found no new node, like 3-4 here. Compare colors on every edge, not only on edges that color a node.

Variations

Students on one side and courses on the other form a bipartite graph. Matching algorithms start from this shape.

A grid is always bipartite: cells alternate between A and B like a chessboard. An odd cycle is what breaks it.

Code

Pseudocode

isBipartite(graph)
  color[every node] ← none
  for each node s
    if color[s] is none
      color[s] ← A; queue ← [s]
      while queue is not empty
        u ← remove the front of queue
        for each neighbor v of u
          if color[v] is none
            color[v] ← the other color than color[u]; add v to queue
          else if color[v] = color[u]
            return false
  return true

Python

from collections import deque

def is_bipartite(adj):
    color = [None] * len(adj)
    for s in range(len(adj)):
        if color[s] is not None:
            continue
        color[s] = 0
        queue = deque([s])
        while queue:
            u = queue.popleft()
            for v in adj[u]:
                if color[v] is None:
                    color[v] = 1 - color[u]
                    queue.append(v)
                elif color[v] == color[u]:
                    return False
    return True

JavaScript

function isBipartite(adj) {
  const color = new Array(adj.length).fill(-1);
  for (let s = 0; s < adj.length; s++) {
    if (color[s] !== -1) continue;
    color[s] = 0;
    const queue = [s];
    for (let head = 0; head < queue.length; head++) {
      const u = queue[head];
      for (const v of adj[u]) {
        if (color[v] === -1) {
          color[v] = 1 - color[u];
          queue.push(v);
        } else if (color[v] === color[u]) {
          return false;
        }
      }
    }
  }
  return true;
}

Cost at a glance

TimeO(V + E)
SpaceO(V)
InputUndirected graph
OutputTwo-coloring or an odd cycle

Practice problems (5)

Which graph can be 2-colored? Warm-up

Two colors must be assigned so that the two ends of every edge differ. Pick the graph where this is possible.

Is the graph bipartite? Standard

Return true if the nodes of the undirected graph can be split into two groups so that every edge joins a node of one group to a node of the other. Otherwise return false. In JavaScript, buildAdjacency(graph) returns the adjacency lists.

Possible bipartition Standard

There are n people, numbered 0 to n - 1. Each pair [a, b] in dislikes means person a and person b dislike each other and cannot be in the same team.

Return true if everyone can be split into two teams (either team may be empty) so that no pair of people who dislike each other share a team. Otherwise return false.

Return the 2-coloring Standard

Return an array colors of length n with every value 0 or 1, so that every edge joins nodes of different colors. In each connected part, the lowest-numbered node gets color 0. If no such coloring exists, return []. In JavaScript, buildAdjacency(graph) returns the adjacency lists.

Odd cycle witness Standard

BFS 2-colors this graph from node 0 and stops at a conflict. Nodes and their colors are shown.

Click every node on the odd cycle that makes 2-coloring impossible.

Related topics

Next on the path: Topological sort: Kahn's algorithm and DFS finishing order