Skip to lesson

Bipartite graphs

A bipartite graph has vertices divided into two independent sets with no internal edges.

What a bipartite graph is and the 2-colouring problem

A bipartite graph is one whose nodes can be split into two groups so that every edge connects a node in one group to a node in the other.

A graph is bipartite if its vertices split into two sets so that every edge joins a vertex of one set to a vertex of the other. We test it by trying to 2-colour the vertices.

TwoColoringCheck.javaJava
public class TwoColoringCheck {    public static void main(String[] args) {        int[][] square = {{0, 1}, {1, 2}, {2, 3}, {3, 0}}; // a 4-cycle        int[] color = {0, 1, 0, 1};                        // alternate colors        boolean ok = true;        for (int[] e : square) {            if (color[e[0]] == color[e[1]]) ok = false;    // edge inside one set        }        System.out.println("square splits into two sets: " + ok);    }}
Output
square splits into two sets: true

Give the start vertex colour 0 and its neighbours colour 1. Every edge must join opposite colours; if one joins two vertices of the same colour, the graph is not bipartite.

Equivalently, a graph is bipartite exactly when it has no odd-length cycle: a 4-cycle is bipartite, a triangle or a 5-cycle is not.

2-colouring using BFS and DFS traversals

To test bipartiteness, maintain an integer array colour of size V initialized to -1. Value -1 means uncolored, while 0 and 1 represent the two contrasting colours.

Example 1 · Bipartite Graph Check Using BFS

Main.javaJava
import java.util.*;
public class Main {    static boolean isBipartite(int[][] graph) {        int n = graph.length;        int[] color = new int[n];        Arrays.fill(color, -1);
        for (int i = 0; i < n; i++) {            if (color[i] == -1) {                if (!bfsCheck(i, graph, color)) return false;            }        }        return true;    }
    static boolean bfsCheck(int start, int[][] graph, int[] color) {        Queue<Integer> q = new LinkedList<>();        color[start] = 0;        q.offer(start);
        while (!q.isEmpty()) {            int u = q.poll();            for (int v : graph[u]) {                if (color[v] == -1) {                    color[v] = 1 - color[u]; // Opposite color                    q.offer(v);                } else if (color[v] == color[u]) {                    return false; // Same color conflict                }            }        }        return true;    }
    public static void main(String[] args) {        // Square graph: 0-1, 1-2, 2-3, 3-0 (Bipartite)        int[][] g1 = {{1, 3}, {0, 2}, {1, 3}, {0, 2}};        // Triangle graph: 0-1, 1-2, 2-0 (Not bipartite)        int[][] g2 = {{1, 2}, {0, 2}, {0, 1}};
        System.out.println("Square graph bipartite: " + isBipartite(g1));        System.out.println("Triangle graph bipartite: " + isBipartite(g2));    }}
Output
Square graph bipartite: true
Triangle graph bipartite: false

What this code does

  • colour array tracks -1 (uncolored), 0 (first colour), and 1 (second colour).
  • Square 4-cycle can be 2-coloured with alternating colours.
  • Triangle 3-cycle forces two adjacent nodes to share colour 1, returning false.

Example 2 · Bipartite Graph Check Using DFS

Main.javaJava
import java.util.*;
public class Main {    static boolean isBipartiteDfs(int[][] graph) {        int n = graph.length;        int[] color = new int[n];        Arrays.fill(color, -1);
        for (int i = 0; i < n; i++) {            if (color[i] == -1) {                if (!dfs(i, 0, graph, color)) return false;            }        }        return true;    }
    static boolean dfs(int u, int c, int[][] graph, int[] color) {        color[u] = c;        for (int v : graph[u]) {            if (color[v] == -1) {                if (!dfs(v, 1 - c, graph, color)) return false;            } else if (color[v] == c) {                return false;            }        }        return true;    }
    public static void main(String[] args) {        int[][] graph = {{1, 3}, {0, 2}, {1, 3}, {0, 2}};        System.out.println("DFS bipartite: " + isBipartiteDfs(graph));    }}
Output
DFS bipartite: true

What this code does

  • dfs assigns alternating colour 1 - c to unvisited neighbours recursively.
  • Colour conflict immediately bubbles false up the call stack.
  • Outer loop ensures disconnected components are thoroughly checked.

In BFS, colour the start node 0 and enqueue it. While queue is not empty, poll vertex u. For each neighbour v, if v is uncolored, assign colour[v] = 1 - colour[u] and enqueue v. If neighbour v is already coloured and colour[v] == colour[u], return false immediately. In DFS, pass the expected colour recursively to each unvisited neighbour. If an already coloured neighbour matches the current colour, return false. An outer loop over vertices 0 to V - 1 handles disconnected graphs in O(V + E) time.

Order of execution

Put 2-colouring in order

Check a graph with BFS colouring. Put the steps in the order the code runs them.

Real-world applications: Splitting people into two rival teams

Sports leagues and matchmakers frequently solve the Possible Bipartition problem. Given N players and a list of mutual dislikes, can we divide all players into two teams? Players who dislike each other cannot be placed on the same team.

Example 3 · Possible Bipartition: Splitting Players into Two Teams

Main.javaJava
import java.util.*;
public class Main {    static boolean possibleBipartition(int n, int[][] dislikes) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());        for (int[] d : dislikes) {            adj.get(d[0]).add(d[1]);            adj.get(d[1]).add(d[0]);        }
        int[] color = new int[n + 1];        Arrays.fill(color, -1);
        for (int i = 1; i <= n; i++) {            if (color[i] == -1 && !bfs(i, adj, color)) return false;        }        return true;    }
    static boolean bfs(int start, List<List<Integer>> adj, int[] color) {        Queue<Integer> q = new LinkedList<>();        color[start] = 0;        q.offer(start);
        while (!q.isEmpty()) {            int u = q.poll();            for (int v : adj.get(u)) {                if (color[v] == -1) {                    color[v] = 1 - color[u];                    q.offer(v);                } else if (color[v] == color[u]) {                    return false;                }            }        }        return true;    }
    public static void main(String[] args) {        int[][] d1 = {{1, 2}, {1, 3}, {2, 4}};        int[][] d2 = {{1, 2}, {1, 3}, {2, 3}};        System.out.println("Can split d1: " + possibleBipartition(4, d1));        System.out.println("Can split d2: " + possibleBipartition(3, d2));    }}
Output
Can split d1: true
Can split d2: false

What this code does

  • Dislike pairs build an undirected conflict graph.
  • Conflict d1 has no odd cycles and cleanly splits into two teams.
  • Conflict d2 forms a 3-person mutual dislike triangle, returning false.

We model players as vertices and mutual dislike pairs as undirected edges. Checking if this conflict graph is bipartite solves team allocation. If bipartite, group 0 forms team A and group 1 forms team B. Job scheduling and recommendation engines use bipartite matching to pair applicants with open jobs.

Next step

Check your understanding

10 quick questions