Home
DSA Visualizer
Data Structures
Bipartite Graph
Bipartite Graph
A bipartite graph is one whose vertices can be split into two groups with every edge running between them; 2-coloring with BFS or DFS tests whether a graph is bipartite. It is essential for matching problems and cycle analysis.
SEED SET A
Set A
Set B
Empty
A is uncoloured and unreached. Put it in set A and grow outwards.
Next
B touches A, so it must go in the opposite set — set B.
Intuition
Can you divide a group of people into two teams such that no two teammates are friends?
If you can, the network of friendships is a Bipartite Graph.
We solve this by trying to color the graph with just two colors (in the figure, blue for Set A and green for Set B).
Concept
- Bipartite Graph: A graph where vertices can be split into two sets, U and V, such that every edge connects a vertex in U to one in V.
- 2-Coloring: If we can color every node with one of two colours such that no two connected nodes have the same color, the graph is bipartite.
- Odd Cycle Property: A graph is bipartite if and only if it contains no odd cycles.
How it Works
- Initialize an array
colorwith 0 (uncolored) for all nodes. - Iterate through all nodes. If uncolored, start BFS:
- Color the start node 1.
- For each neighbor:
- If uncolored: Color it with the opposite color (2 if current is 1, 1 if current is 2) and push to queue.
- If already colored with same color: Conflict found! Return false.
- If traversal completes without conflict, return true.
Step-by-Step Breakdown
Watch the visualization:
- Blue node: Assigned to Set A, where the search starts.
- Green node: Assigned to Set B.
- Red nodes and edge: Two joined nodes landed in the same set. Graph is NOT bipartite.
- Set A and Set B: The panels list the members of each set.
When to Use
Use Bipartite Check when:
- Allocating resources into two independent sets.
- Stable Marriage problem and other matching algorithms.
- Detecting odd cycles in a graph.
When NOT to Use
- Directed Graphs: The definition applies to undirected graphs (though similar concepts exist for directed acyclicity).
How to Identify
"Can we split into two groups?", "Is there an odd cycle?", "2-Coloring possible?".
Applying for software engineering roles? Free, no sign-up:
