Understanding the Problem
A graph is bipartite if you can divide its set of vertices into two groups such that no two vertices within the same group are adjacent. In simple terms, adjacent vertices must always belong to opposite groups.
Using DFS to Check Bipartiteness
We use Depth-First Search (DFS) to try and color each node of the graph using two colors (say, 0 and 1). If any adjacent node has the same color, the graph is not bipartite.
Handling Different Scenarios
Case 1: Connected Graph
Start from any node and use DFS to color the graph. If you can color the entire graph without any two connected nodes having the same color, the graph is bipartite.
Case 2: Disconnected Graph
If the graph has multiple disconnected components, we need to perform DFS from each unvisited node. Each component must independently satisfy the bipartite condition.
Case 3: Presence of Odd-Length Cycle
Any graph containing an odd-length cycle cannot be bipartite. While coloring, you’ll find a point where two adjacent nodes need the same color—this is your cue the graph is not bipartite.
Case 4: Empty Graph
An empty graph (with zero edges) is trivially bipartite because there are no edges to violate the bipartite rule.
Conclusion
If all nodes (across all components) can be colored with two alternating colors using DFS without conflict, the graph is bipartite. Otherwise, it is not.