Python 3D Academyবাংলা

Two teams, and copying a graph

🌍 In real life. A class is split into two teams for a quiz, but some pairs of friends always chat, so the teacher wants every such pair on opposite teams. Is that possible? With Ana–Bo, Ana–Cy, Bo–Di and Cy–Di, yes. Add Bo–Cy, and Ana, Bo and Cy form a triangle: two of them must end up together.

A graph whose vertices can be split into two sides so that every edge crosses between them is called bipartite (LeetCode 785, 886). And a second classic: making a full, separate copy of a graph whose nodes point to each other (LeetCode 133).

The idea in one sentence: colour the graph with a BFS, giving each newly reached vertex the opposite team of the vertex it was reached from, and if an edge ever joins two vertices of the same team, no split exists; to copy a graph, walk it once, keeping a dict from each original node to its copy so that a node met twice is copied only once.

Its words:

  • bipartite: splittable into two sides with every edge going across
  • odd cycle: a cycle with an odd number of edges, like a triangle; a graph is bipartite exactly when it has none
  • deep copy: new nodes and new edges, sharing nothing with the original
  • visited map: copies, original → copy, which stops the walk from looping on a cycle

Step by step, splitting A–B, A–C, B–D, C–D:

  1. A goes to team 0.
  2. A's neighbours B and C go to team 1.
  3. From B: D goes to team 0. From C: D is already in team 0, which is different from C's team 1: fine.
  4. Every edge crosses: the split is {A, D} and {B, C}.

The BFS from A reaches the graph in layers, and the teams simply alternate by layer:

Why it is correct. Inside one connected piece, once the start's team is chosen, BFS forces every other vertex's team: each is the opposite of the vertex it was reached from. So if any split exists, this is it (or the same with the teams swapped), and a clash on some edge proves that no split exists. A clash means a cycle with an odd number of edges, like a triangle: walking round it, the teams alternate and come back wrong. The outer loop over start handles graphs in several pieces.

Copying a graph. Graph nodes point at each other, often in cycles. A plain recursive copy would follow A → B → A → B for ever. The copies dict fixes it: before following a node's edges, store its copy; when the walk meets that node again, it reuses the copy, so every node is copied exactly once and the copies point at copies, never at the originals.

What it costs, by counting. Both visit every vertex once and look at every edge (twice, once from each end): O(V + E) time, O(V) memory for team or copies and the queue.

from collections import deque


def two_teams(graph):                       # graph: {vertex: [neighbours]}
    team = {}
    for start in graph:                     # every piece of the graph
        if start in team:
            continue
        team[start] = 0
        queue = deque([start])
        while queue:
            v = queue.popleft()
            for w in graph[v]:
                if w not in team:
                    team[w] = 1 - team[v]   # the other team
                    queue.append(w)
                elif team[w] == team[v]:
                    return None             # an edge inside one team
    return team


square = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"]}
triangle = {"A": ["B", "C"], "B": ["A", "C"], "C": ["A", "B"]}
print(two_teams(square))
print(two_teams(triangle))


class GNode:
    def __init__(self, val):
        self.val = val
        self.neighbors = []


def clone(node):
    copies = {}                             # original node -> its copy

    def copy(n):
        if n in copies:
            return copies[n]
        c = GNode(n.val)
        copies[n] = c                       # remember it BEFORE following edges
        c.neighbors = [copy(m) for m in n.neighbors]
        return c

    return copy(node) if node else None


a, b = GNode(1), GNode(2)
a.neighbors, b.neighbors = [b], [a]          # a cycle of two
c = clone(a)
print(c.val, c.neighbors[0].val, c.neighbors[0].neighbors[0] is c, c is not a)
The copy keeps the cycle (the copy of b points back at the copy of a) and shares no node with the original.

Mistakes and edge cases.

  • Starting only from one vertex. A graph in two pieces has a second piece the BFS never reaches; loop over every vertex and start a new BFS from any vertex without a team.
  • Checking only new vertices. The clash test must run on vertices already in a team too; that is where an odd cycle shows up.
  • Storing the copy after the recursion. In copy, copies[n] = c must come before following the neighbours; after them, a cycle recurses for ever and stops with RecursionError.
  • A shallow copy. copy.copy(node) makes a new node whose neighbors list still holds the original nodes.
  • Directed graphs. Bipartite is about undirected edges; for a directed edge list, add both directions first.

Quiz

  1. What does this print?

    from collections import deque
    
    
    def two_teams(graph):                       # graph: {vertex: [neighbours]}
        team = {}
        for start in graph:                     # every piece of the graph
            if start in team:
                continue
            team[start] = 0
            queue = deque([start])
            while queue:
                v = queue.popleft()
                for w in graph[v]:
                    if w not in team:
                        team[w] = 1 - team[v]   # the other team
                        queue.append(w)
                    elif team[w] == team[v]:
                        return None             # an edge inside one team
        return team
    
    
    path = {"A": ["B"], "B": ["A", "C"], "C": ["B"], "X": ["Y"], "Y": ["X"]}
    print(two_teams(path))
  2. Which of these graphs is NOT bipartite?

    • A cycle of 5 vertices
    • A cycle of 4 vertices
    • A tree
  3. While copying a graph, why keep a dict from each original node to its copy?

    • So a node reached twice is copied once, and cycles don't loop for ever
    • To sort the nodes
    • Python can't copy objects without it
  4. Copying two nodes that point at each other stops with RecursionError. Which line is wrong?

    def clone(node):
        copies = {}
    
        def copy(n):
            if n in copies:
                return copies[n]
            c = GNode(n.val)
            c.neighbors = [copy(m) for m in n.neighbors]
            copies[n] = c
            return c
    
        return copy(node)

Coding tasks

  1. Write can_split(graph): True if the undirected graph (a dict from each vertex to its neighbours) is bipartite, False if not. It may be in several pieces.

  2. Write clone(node) that makes a deep copy of the graph reachable from node (each GNode has val and a neighbors list) and returns the copy of node (None for None).