Can every node get one of two colours so no edge joins a matching pair? Paint each component by BFS and stop at the first clash.
▼The problem
LeetCode 785 (Medium). Given an undirected graph as adjacency lists graph[u], return true if its nodes can be split into two sets so that every edge joins a node in one set to a node in the other. The graph may be disconnected.
Examples (LeetCode's): graph = [[1,3],[0,2],[1,3],[0,2]] → true (sets {0, 2} and {1, 3}) and graph = [[1,2,3],[0,2],[0,1,3],[0,2]] → false (0, 1 and 2 form a triangle).
The solution
def isBipartite(graph):
color = [-1] * len(graph)
for start in range(len(graph)):
if color[start] != -1: continue
color[start] = 0
queue = deque([start])
while queue:
u = queue.popleft()
for v in graph[u]:
if color[v] == -1:
color[v] = 1 - color[u]
queue.append(v)
elif color[v] == color[u]:
return False
return TrueTranscript
Is Graph Bipartite? You get an undirected graph as adjacency lists: for each node, the nodes it links to. Can you split the nodes into two teams so every edge joins the two teams?
Take a square. Zero links to one and three, and two links to one and three. Give zero and two orange scarves, and one and three blue. Every edge joins orange to blue: true. Now add a diagonal from zero to two. Zero, one and two form a triangle, and whichever team two picks, it matches a neighbor. False.
The naive way tries every split. Each node is orange or blue, so n nodes make two to the n splits, and each one checks every edge. Four nodes is sixteen splits; thirty nodes is over a billion.
Better: hand out scarves as you go. Give an unscarved node orange, then visit its neighbors breadth first, giving each the opposite color. If a neighbor already wears your color, that's a clash. You've closed a loop with an odd number of edges, and an odd loop can't alternate. Return false.
A graph can also come in separate pieces, so loop over every node, and start a fresh search from any node still without a scarf.
In code, a color array starts at minus one for everyone. Each uncolored start gets zero and joins a queue. Pop a node and look at its neighbors. Uncolored? Give it one minus your color, and queue it. The same color as you? Return false. If every piece finishes, return true.
Let's run it on the square with the diagonal. Zero is orange. Pop zero, and one, two and three all turn blue. Pop one. Zero is orange, fine. But two is blue, just like one. Clash! Return false.
Each node joins the queue once, and each edge is checked from both ends. That's order V plus E time, and order V space for the colors and the queue.
Two colors, flip across every edge, stop at a clash. That's Is Graph Bipartite.