Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Ford–Fulkerson algorithm
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Python implementation of the Edmonds–Karp algorithm== <syntaxhighlight lang="python" line="1"> import collections class Graph: """ This class represents a directed graph using adjacency matrix representation. """ def __init__(self, graph): self.graph = graph # residual graph self.row = len(graph) def bfs(self, s, t, parent): """ Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path. """ # Mark all the vertices as not visited visited = [False] * self.row # Create a queue for BFS queue = collections.deque() # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True # Standard BFS loop while queue: u = queue.popleft() # Get all adjacent vertices of the dequeued vertex u # If an adjacent has not been visited, then mark it # visited and enqueue it for ind, val in enumerate(self.graph[u]): if (visited[ind] == False) and (val > 0): queue.append(ind) visited[ind] = True parent[ind] = u # If we reached sink in BFS starting from source, then return # true, else false return visited[t] # Returns the maximum flow from s to t in the given graph def edmonds_karp(self, source, sink): # This array is filled by BFS and to store path parent = [-1] * self.row max_flow = 0 # There is no flow initially # Augment the flow while there is path from source to sink while self.bfs(source, sink, parent): # Find minimum residual capacity of the edges along the # path filled by BFS. Or we can say find the maximum flow # through the path found. path_flow = float("Inf") s = sink while s != source: path_flow = min(path_flow, self.graph[parent[s]][s]) s = parent[s] # Add path flow to overall flow max_flow += path_flow # update residual capacities of the edges and reverse edges # along the path v = sink while v != source: u = parent[v] self.graph[u][v] -= path_flow self.graph[v][u] += path_flow v = parent[v] return max_flow </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)