2Brute2Best
🔥0
06

Bipartite / two-colouring (Graph BFS / DFS Sub-pattern)

Can the nodes be split into two groups so that every edge goes between the groups?

Signals in the problem statement
  • ›

    "two groups", "bipartite", "two teams"

  • ›

    "people who dislike each other can't be in the same group"

What makes it different

Is Graph Bipartite gets the adjacency list directly. Possible Bipartition first builds an undirected graph from the dislike pairs (1-indexed). Both two-colour every component; one same-colour edge is enough to answer false.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Is Graph Bipartite?
    Basic Anchor·LeetCode #785
    Medium
  2. 2
    Possible Bipartition
    Basic Reinforcement·LeetCode #886
    Medium

Template

bipartite-template.cpp
// Two-colouring: give a node colour 0, its neighbours colour 1, and so on; a same-colour edge = not bipartite.
bool isBipartite(const vector<vector<int>>& adj) {
    int n = adj.size();
    vector<int> color(n, -1);
    for (int s = 0; s < n; s++) {                // every component, not just node 0
        if (color[s] != -1) continue;
        color[s] = 0;
        queue<int> q;
        q.push(s);
        while (!q.empty()) {
            int u = q.front(); q.pop();
            for (int v : adj[u]) {
                if (color[v] == -1) { color[v] = 1 - color[u]; q.push(v); }
                else if (color[v] == color[u]) return false;   // an odd cycle
            }
        }
    }
    return true;
}
Remember this · Graph BFS / DFS
Trigger
Grid of cells, islands, regions, "minimum steps", transformations between states, connected components.
Think
What is a node, what is an edge, and do I need the shortest path or just reachability?
Key question
How do I mark visited so I never process a node twice?