arundeepak

Ford Fulkerson Algorithm to find maximum flow

Mar 28th, 2016
537
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. '__author__'=='deepak Singh Mehta(learning maximum flow... :))'
  2.  
  3. #Ford Fulkerson Algorithm..
  4.  
  5. graph,V,int_max = list(),6,999999
  6.  
  7. def bfs(s,t,parent):
  8.     global V,graph
  9.     vis =[False for i in range(V)] #to keep track of visited nodes
  10.     q = list() #this is our queue to traverse the dfs
  11.     q.insert(0,s)
  12.     vis[s]=True
  13.     parent[s]=-1
  14.     while len(q)!=0:
  15.         u = q.pop()
  16.         for i in range(V):
  17.             if not vis[i] and graph[u][i]>0:
  18.                 q.insert(0,i)
  19.                 parent[i]=u
  20.                 vis[i]=True
  21.     return vis[t] #Start from source and if we reach the sink, then sink(t) should
  22.                   # be visited , it returns the same.
  23.  
  24.  
  25. def fordFulkerson(s,t):
  26.     global graph,V,int_max
  27.     parent, max_flow = [0 for i in range(V)],0
  28.     #There is an augumented path from src to sink(s to t) if bfs returns true
  29.     while bfs(s,t,parent):
  30.         path_flow = int_max
  31.         v = t
  32.         while v!=s:
  33.             u = parent[v]
  34.             path_flow = min(path_flow,graph[u][v])#choose flow for this augumented path.
  35.             v = parent[v] #to trace the path (child->parent)
  36.         v = t
  37.         while v!=s: #to update residual capacity
  38.             u = parent[v]
  39.             graph[u][v]-= path_flow #update the min. path flow on traced path edge
  40.             graph[v][u]+= path_flow #update the same on backedge
  41.             v = parent[v]
  42.         max_flow += path_flow #adding all the min. path flows to get final max flow
  43.     return max_flow
  44.            
  45.  
  46. if __name__=='__main__':
  47.     graph = [[0,16,13,0,0,0],
  48.              [0,0,10,12,0,0],
  49.              [0,4,0,0,14,0],
  50.              [0,0,9,0,0,20],
  51.              [0,0,0,7,0,4],
  52.              [0,0,0,0,0,0]
  53.              ]
  54.     src = 0 #source node
  55.     sink = 5 #sinking node
  56.     print("The maximum possible flow is",fordFulkerson(src,sink))
Add Comment
Please, Sign In to add comment