CodeBlanks Logo Icon CodeBlanks

Challenge 4

Print the maximum flow.

Challenge 4 - Maximum flow

The fourth challenge tests the Ford-Fulkerson maximum flow algorithm. It grows flow via augmenting paths and adds the bottleneck of each path to the total.

The count_doublings, kmp_search and convex_hull functions are provided above; you will write ford_fulkerson. Find augmenting paths with DFS, push the bottleneck.

This challenge is the fourth link of the cumulative chain and tests network flow.

Practice ford_fulkerson function

Write ford_fulkerson(capacity, source, sink). Return the maximum flow. Print 5 with print(ford_fulkerson([('s','a',3), ('s','b',2), ('a','t',2), ('b','t',3), ('a','b',1)], 's', 't')). The other three functions are provided above.

Starter code

solution.py
def count_doublings(n):
    count = 0
    size = 1
    last = 0
    for i in range(n):
        if last == size:
            size *= 2
            count += 1
        last += 1
    return count

def kmp_search(text, pattern):
    n, m = len(text), len(pattern)
    lps = [0] * m
    length = 0
    i = 1
    while i < m:
        if pattern[i] == pattern[length]:
            length += 1
            lps[i] = length
            i += 1
        elif length != 0:
            length = lps[length - 1]
        else:
            lps[i] = 0
            i += 1
    i = j = 0
    while i < n:
        if text[i] == pattern[j]:
            i += 1
            j += 1
            if j == m:
                return i - j
        elif j != 0:
            j = lps[j - 1]
        else:
            i += 1
    return -1

def convex_hull(points):
    pts = sorted(set(points))
    if len(pts) <= 1:
        return pts
    def cross(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
    lower = []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    upper = []
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    return lower[:-1] + upper[:-1]

def ford_fulkerson(capacity, source, sink):
    # Return the maximum flow

Sample solution

solution.py
def ford_fulkerson(capacity, source, sink):
    from collections import defaultdict
    graph = defaultdict(dict)
    for u, v, c in capacity:
        graph[u][v] = graph[u].get(v, 0) + c
        graph[v][u] = graph[v].get(u, 0)
    max_flow = 0
    def dfs(s, t, flow, visited):
        if s == t:
            return flow
        visited.add(s)
        for v in graph[s]:
            if v not in visited and graph[s][v] > 0:
                pushed = dfs(v, t, min(flow, graph[s][v]), visited)
                if pushed > 0:
                    graph[s][v] -= pushed
                    graph[v][s] = graph[v].get(s, 0) + pushed
                    return pushed
        return 0
    while True:
        f = dfs(source, sink, float('inf'), set())
        if f == 0:
            break
        max_flow += f
    return max_flow
print(ford_fulkerson([('s','a',3), ('s','b',2), ('a','t',2), ('b','t',3), ('a','b',1)], 's', 't'))

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the maximum flow equal to?

  • The longest path
  • Total edges
  • Source degree
  • The minimum cut capacity Correct answer

Explanation: Maximum flow equals the minimum cut capacity.

2 Max-flow concepts

Term Meaning
augmenting path Push flow
bottleneck Minimum capacity
max_flow Flow accumulation
DFS Path search

3 flow accumulation

Question
max_flow += ____
Answer
max_flow += f

Explanation: Each augmenting path's bottleneck f is added.

All lessons in Expert