Example 1
- Input
- graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
- Output
- false
Nodes 0, 1 and 2 form a triangle, and three mutually adjacent nodes cannot fit into two groups.
Given an adjacency list of an undirected graph, decide whether its nodes split into two groups with every edge crossing between groups. Odd-length cycles make this impossible.
You are given an undirected graph with n nodes (0 to n - 1) as an adjacency list graph, where graph[u] lists the neighbours of u.
Return true exactly when the graph is bipartite: its nodes split into two sets A and B so that every edge joins a node in A to a node in B.
Nodes 0, 1 and 2 form a triangle, and three mutually adjacent nodes cannot fit into two groups.
Split into {0, 2} and {1, 3}: every edge runs from one group to the other.
There are no edges to violate the rule. The isolated node may be assigned to either group; the other group may be empty.
The component containing 0 and 1 splits cleanly, but nodes 2, 3 and 4 form a triangle. Every component must be bipartite, so checking only node 0's component would miss the failure.
The single edge 1-2 puts its endpoints in opposite groups. Isolated nodes 0 and 3 impose no additional constraints.
Place one node in group 0 and every neighbor in group 1; repeat this forced alternation along paths. A triangle creates a contradiction because two adjacent neighbors of 0 must both receive group 1. Example 1 exposes exactly that conflict. Different connected components can choose their starting group independently, so the traversal must restart at every unassigned node. The numbers 0 and 1 are group labels, and -1 means unassigned.
Reveal BFS Coloring: intuition, complexity, and code
Bipartiteness is two-colouring by force: propagate opposite colours and read the first conflict as proof of an odd cycle.