Skip to content

Commit f052de5

Browse files
committed
feat: maximum-flow-edmonds-karp challenge
1 parent 9a1bc9f commit f052de5

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from collections import deque
2+
from typing import List
3+
4+
class EdmondsKarp:
5+
def __init__(self, graph: List[List[int]]):
6+
self.graph = graph
7+
self.n = len(graph)
8+
self.residual_graph = [row[:] for row in graph]
9+
10+
def bfs(self, source: int, sink: int, parent: List[int]) -> bool:
11+
visited = [False] * self.n
12+
queue = deque([source])
13+
visited[source] = True
14+
15+
while queue:
16+
u = queue.popleft()
17+
for v, capacity in enumerate(self.residual_graph[u]):
18+
if not visited[v] and capacity > 0:
19+
queue.append(v)
20+
visited[v] = True
21+
parent[v] = u
22+
if v == sink:
23+
return True
24+
return False
25+
26+
def max_flow(self, source: int, sink: int) -> int:
27+
parent = [-1] * self.n
28+
max_flow = 0
29+
30+
while self.bfs(source, sink, parent):
31+
path_flow = float('inf')
32+
s = sink
33+
while s != source:
34+
path_flow = min(path_flow, self.residual_graph[parent[s]][s])
35+
s = parent[s]
36+
37+
max_flow += path_flow
38+
39+
v = sink
40+
while v != source:
41+
u = parent[v]
42+
self.residual_graph[u][v] -= path_flow
43+
self.residual_graph[v][u] += path_flow
44+
v = parent[v]
45+
46+
return max_flow
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Challenge: Develop the Edmonds-Karp algorithm to calculate the maximum flow in a network.
2+
# This challenge deepens advanced graph handling and data structures to improve efficiency.
3+
# Use object-oriented programming and follow the DRY principle.
4+
5+
from edmonds_karp import EdmondsKarp
6+
7+
def main():
8+
graph = [
9+
[0, 16, 13, 0, 0, 0],
10+
[0, 0, 10, 12, 0, 0],
11+
[0, 4, 0, 0, 14, 0],
12+
[0, 0, 9, 0, 0, 20],
13+
[0, 0, 0, 7, 0, 4],
14+
[0, 0, 0, 0, 0, 0]
15+
]
16+
ek = EdmondsKarp(graph)
17+
max_flow = ek.max_flow(0, 5)
18+
print(f"Maximum flow: {max_flow}")
19+
20+
if __name__ == "__main__":
21+
main()

0 commit comments

Comments
 (0)