Check a bipartite graph
Return whether an undirected graph can be colored with two colors so adjacent vertices differ. The dict includes every vertex and symmetric adjacency; disconnected graphs and self-loops are permitted.
colors = {0: 0}
node, neighbour = 0, 1
colors[neighbour] = 1-colors[node]
print(colors)Reason about the state
Start a two-color breadth-first search from every uncolored component. An edge joining equal colors proves failure, including a self-loop. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return whether an undirected graph can be colored with two colors so adjacent vertices differ. The dict includes every vertex and symmetric adjacency; disconnected graphs and self-loops are permitted.
The explanation opens here once every check passes.