Is Graph Bipartite?
Can the nodes be split into two sets so every edge crosses between the sets? (2-colorability.)
Open on LeetCode ↗Intuition
Bipartite means 2-colorable: paint a node red, all its neighbors blue, their neighbors red, and so on. If the paint spreads without ever forcing a node to take both colors, the two colors are the two sets. A conflict happens exactly when the graph has an odd cycle — the color parity comes back wrong.
Approach
Color while traversing
color[] starts uncolored. For each uncolored node (graph may be disconnected), start a BFS or DFS: color the start 0, and give every neighbor the opposite color of its parent.
Detect the contradiction
When traversal meets an already-colored neighbor, it must have the opposite color. Same color = odd cycle = not bipartite, return false immediately.
BFS vs DFS
Identical logic either way — this covers both the BFS and DFS variants of the sheet. Only the visit order differs; the coloring rule and conflict test are the same.
Solution & live demo
Edge cases
Outer loop restarts coloring in every uncolored component.
Trivially bipartite.
A node adjacent to itself needs both colors — immediately false.