Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created October 6, 2023 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheAlchemistKE/3c6042e338969ccb32a634a2aeb97384 to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/3c6042e338969ccb32a634a2aeb97384 to your computer and use it in GitHub Desktop.
from collections import defaultdict
class HopcroftKarp:
def __init__(self, graph):
self.graph = graph
self.matching = {}
self.visited = set()
def bipartite_matching(self):
for u in self.graph.keys():
if u not in self.matching:
self.visited = set()
if self.dfs(u):
self.visited.clear()
return self.matching
def dfs(self, u):
if u in self.visited:
return False
self.visited.add(u)
for v in self.graph[u]:
if v not in self.matching or self.dfs(self.matching[v]):
self.matching[u] = v
self.matching[v] = u
return True
return False
# Example usage:
graph = {
'A': ['X', 'Y'],
'B': ['X'],
'C': ['Y'],
'D': []
}
hk = HopcroftKarp(graph)
matching = hk.bipartite_matching()
print(matching)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment