Data Structures & AlgorithmsVery hardProduct company OA

BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)?

BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)?
from collections import deque
n = 9
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 4), (7, 8)]
adj = [[] for _ in range(n)]
for a, b in edges: adj[a].append(b); adj[b].append(a)
col = [-1] * n; bip = comps = 0
for s in range(n):
    if col[s] != -1: continue
    comps += 1; col[s] = 0; ok = True; q = deque([s])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if col[v] == -1: col[v] = col[u] ^ 1; q.append(v)
            elif col[v] == col[u]: ok = False
    bip += ok
print(comps, bip)
  1. A. 3 3
  2. B. 4 2
  3. C. 3 1
  4. D. 3 2

Correct answer: D. 3 2

A component is bipartite iff it has no odd cycle; the BFS detects that as an edge joining two vertices of the same colour. Component {0, 1, 2, 3} is a 4-cycle (even → bipartite), {4, 5, 6} a triangle (odd → not), {7, 8} a single edge (bipartite). The colouring must restart in every uncoloured vertex, otherwise components are silently skipped. O(V + E).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic