Created
July 20, 2020 03:55
-
-
Save chez-shanpu/c0b2622ce4fa99638bdb46d458dfb3f1 to your computer and use it in GitHub Desktop.
BipartiteMatching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// refer https://www.geeksforgeeks.org/maximum-bipartite-matching/ | |
package main | |
import "fmt" | |
func BPM(graph [][]bool, m, n int) []int { | |
matchR := make([]int, n) | |
matchR, _ = fill(matchR, -1, 0, len(matchR)) | |
for u := 0; u < m; u++ { | |
seen := make([]bool, n) | |
search(graph, u, seen, matchR, m, n) | |
} | |
return matchR | |
} | |
func search(graph [][]bool, u int, seen []bool, matchR []int, m, n int) bool { | |
for v := 0; v < n; v++ { | |
if graph[u][v] && !seen[v] { | |
seen[v] = true | |
if matchR[v] < 0 || search(graph, matchR[v], seen, matchR, m, n) { | |
matchR[v] = u | |
return true | |
} | |
} | |
} | |
return false | |
} | |
func fill(slice []int, val, start, end int) ([]int, error) { | |
if len(slice) < start || len(slice) < end { | |
return nil, fmt.Errorf("Error") | |
} | |
for i := start; i < end; i++ { | |
slice[i] = val | |
} | |
return slice, nil | |
} | |
func main() { | |
graph := [][]bool{ | |
{false, true, true}, | |
{false, false, true}, | |
{true, true, false}, | |
} | |
m := 3 | |
n := 3 | |
matchR := BPM(graph, m, n) | |
fmt.Println("Pairs (s, t)") | |
for i, v := range matchR { | |
fmt.Printf("(%d, %d)\n", v, i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment