Uploaded by riya shah

60004200118 AA EXP7

advertisement
ADVANCED ALGORITHMS
EXPERIMENT 7
Name: Riya J. Shah
SAP id: 60004200118
Batch: B/B3
Branch: Computer Engineering
AIM:
Implementation of Ford Fulkerson.
THEORY:
The Ford-Fulkerson algorithm is a widely used algorithm to solve the
maximum flow problem in a flow network. The maximum flow problem
involves determining the maximum amount of flow that can be sent from a
source vertex to a sink vertex in a directed weighted graph, subject to
capacity constraints on the edges.
The algorithm works by iteratively finding an augmenting path, which is a
path from the source to the sink in the residual graph, i.e., the graph
obtained by subtracting the current flow from the capacity of each edge. The
algorithm then increases the flow along this path by the maximum possible
amount, which is the minimum capacity of the edges along the path.
CODE
INF = float('inf')
def bfs(graph, s, t, parent):
visited = [False] * len(graph)
queue = []
queue.append(s)
visited[s] = True
parent[s] = -1
while queue:
u = queue.pop(0)
for v in range(len(graph)):
if not visited[v] and graph[u][v] > 0:
queue.append(v)
visited[v] = True
parent[v] = u
if v == t:
return True
return False
def ford_fulkerson(graph, source, sink):
parent = [-1] * len(graph)
max_flow = 0
while bfs(graph, source, sink, parent):
path_flow = INF
s = sink
path = [s]
while s != source:
path_flow = min(path_flow, graph[parent[s]][s])
s = parent[s]
path.append(s)
max_flow += path_flow
path.reverse()
print("Augmenting path:", path)
print("Max flow for this path:", path_flow)
print("Residual capacity:", [[graph[u][v] for v in range(len(gra
ph))] for u in range(len(graph))])
v = sink
while v != source:
u = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
v = parent[v]
return max_flow
graph = [[0,
[0,
[0,
[0,
[0,
2,
0,
1,
0,
0,
3,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0],
3],
0],
3],
0]]
source = 0
sink = 4
max_flow = ford_fulkerson(graph, source, sink)
print("The maximum flow in the graph is:", max_flow)
OUTPUT
CONCLUSION
Thus, we have successfully implemented Ford Fulkerson.
Download