@@ -455,24 +455,23 @@ def ford_fulkerson(self, start, end):
455455
456456 :param Any start: The start vertex to consider
457457 :param Any end: The target/end vertex to consider
458- :return: True when the end vertex is found, False otherwise
458+ :return: The maximum flow
459459 """
460460
461- if start not in vertices :
462- return ValueError ("Source not in graph" )
463- if end not in vertices :
464- return ValueError ("End not in graph" )
461+ if start not in self . vertices :
462+ raise ValueError ("Source not in graph" )
463+ if end not in self . vertices :
464+ raise ValueError ("End not in graph" )
465465
466466 if end not in self .edges :
467467 self .edges [end ] = {}
468468
469- initial_edges = {a : graph .edges [a ].copy () for a in graph .edges }
470- self .flow_graph = {a : graph .edges [a ].copy () for a in graph .edges }
469+ initial_edges = {a : self .edges [a ].copy () for a in self .edges }
470+ self .flow_graph = {a : self .edges [a ].copy () for a in self .edges }
471471
472472 max_flow = 0
473473 frontier = [start ]
474474 heapq .heapify (frontier )
475- print (self .edges )
476475
477476 while self .breadth_first_search (start , end ):
478477 path_flow = float ("Inf" )
@@ -506,3 +505,38 @@ def ford_fulkerson(self, start, end):
506505 self .edges = initial_edges
507506
508507 return max_flow
508+
509+ def bipartite_matching (self , starts , ends ):
510+ """
511+ Performs a bipartite matching using Fold-Fulkerson's algorithm
512+
513+ :param iterable starts: A list of source vertices
514+ :param iterable ends: A list of target vertices
515+ :return: The maximum matches found
516+ """
517+
518+ start_point = "A"
519+ while start_point in self .vertices :
520+ start_point += "A"
521+ self .edges [start_point ] = {}
522+ self .vertices += start_point
523+ for start in starts :
524+ if start not in self .vertices :
525+ return ValueError ("Source not in graph" )
526+ self .edges [start_point ].update ({start : 1 })
527+
528+ end_point = "Z"
529+ while end_point in self .vertices :
530+ end_point += "Z"
531+ self .vertices .append (end_point )
532+ for end in ends :
533+ if end not in self .vertices :
534+ return ValueError ("End not in graph" )
535+ if end not in self .edges :
536+ self .edges [end ] = {}
537+ self .edges [end ].update ({end_point : 1 })
538+
539+ value = self .ford_fulkerson (start_point , end_point )
540+ self .vertices .remove (end_point )
541+ self .vertices .remove (start_point )
542+ return value
0 commit comments