Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created October 6, 2023 20:03
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/d8dc4fb6a0a5a037b4f34fa9d0fd0a07 to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/d8dc4fb6a0a5a037b4f34fa9d0fd0a07 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
type HopcroftKarp struct {
graph map[string][]string
matching map[string]string
visited map[string]bool
}
func NewHopcroftKarp(graph map[string][]string) *HopcroftKarp {
return &HopcroftKarp{
graph: graph,
matching: make(map[string]string),
visited: make(map[string]bool),
}
}
func (hk *HopcroftKarp) BipartiteMatching() map[string]string {
for u := range hk.graph {
if _, exists := hk.matching[u]; !exists {
hk.visited = make(map[string]bool)
hk.dfs(u)
hk.visited = make(map[string]bool)
}
}
return hk.matching
}
func (hk *HopcroftKarp) dfs(u string) bool {
if hk.visited[u] {
return false
}
hk.visited[u] = true
for _, v := range hk.graph[u] {
if _, exists := hk.matching[v]; !exists || hk.dfs(hk.matching[v]) {
hk.matching[u] = v
hk.matching[v] = u
return true
}
}
return false
}
func main() {
graph := map[string][]string{
"A": []string{"X", "Y"},
"B": []string{"X"},
"C": []string{"Y"},
"D": []string{},
}
hk := NewHopcroftKarp(graph)
matching := hk.BipartiteMatching()
fmt.Println(matching)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment