MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / ford_fulkerson

Function ford_fulkerson

networking_flow/ford_fulkerson.py:58–106  ·  view source on GitHub ↗

This function returns the maximum flow from source to sink in the given graph. CAUTION: This function changes the given graph. Args: graph: Adjacency matrix of graph source: Source sink: Sink Returns: Maximum flow >>> test_graph = [ ...

(graph: list, source: int, sink: int)

Source from the content-addressed store, hash-verified

56
57
58def ford_fulkerson(graph: list, source: int, sink: int) -> int:
59 """
60 This function returns the maximum flow from source to sink in the given graph.
61
62 CAUTION: This function changes the given graph.
63
64 Args:
65 graph: Adjacency matrix of graph
66 source: Source
67 sink: Sink
68
69 Returns:
70 Maximum flow
71
72 >>> test_graph = [
73 ... [0, 16, 13, 0, 0, 0],
74 ... [0, 0, 10, 12, 0, 0],
75 ... [0, 4, 0, 0, 14, 0],
76 ... [0, 0, 9, 0, 0, 20],
77 ... [0, 0, 0, 7, 0, 4],
78 ... [0, 0, 0, 0, 0, 0],
79 ... ]
80 >>> ford_fulkerson(test_graph, 0, 5)
81 23
82 """
83 # This array is filled by breadth-first search and to store path
84 parent = [-1] * (len(graph))
85 max_flow = 0
86
87 # While there is a path from source to sink
88 while breadth_first_search(graph, source, sink, parent):
89 path_flow = int(1e9) # Infinite value
90 s = sink
91
92 while s != source:
93 # Find the minimum value in the selected path
94 path_flow = min(path_flow, graph[parent[s]][s])
95 s = parent[s]
96
97 max_flow += path_flow
98 v = sink
99
100 while v != source:
101 u = parent[v]
102 graph[u][v] -= path_flow
103 graph[v][u] += path_flow
104 v = parent[v]
105
106 return max_flow
107
108
109if __name__ == "__main__":

Callers 1

ford_fulkerson.pyFile · 0.85

Calls 1

breadth_first_searchFunction · 0.70

Tested by

no test coverage detected