-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathHopcroftKarp.cs
187 lines (159 loc) · 6.99 KB
/
HopcroftKarp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
using System;
using System.Collections.Generic;
using Advanced.Algorithms.DataStructures.Graph;
namespace Advanced.Algorithms.Graph;
/// <summary>
/// Compute Max BiParitite Edges using Hopcroft Karp algorithm.
/// </summary>
public class HopcroftKarpMatching<T>
{
/// <summary>
/// Returns a list of Max BiPartite Match Edges.
/// </summary>
public HashSet<MatchEdge<T>> GetMaxBiPartiteMatching(IGraph<T> graph)
{
//check if the graph is BiPartite by coloring 2 colors
var mColorer = new MColorer<T, int>();
var colorResult = mColorer.Color(graph, new[] { 1, 2 });
if (colorResult.CanColor == false) throw new Exception("Graph is not BiPartite.");
return GetMaxBiPartiteMatching(graph, colorResult.Partitions);
}
/// <summary>
/// Get Max Match from Given BiPartitioned Graph.
/// </summary>
private HashSet<MatchEdge<T>> GetMaxBiPartiteMatching(IGraph<T> graph,
Dictionary<int, List<T>> partitions)
{
var matches = new HashSet<MatchEdge<T>>();
var leftToRightMatchEdges = new Dictionary<T, T>();
var rightToLeftMatchEdges = new Dictionary<T, T>();
var freeVerticesOnRight = Bfs(graph, partitions, leftToRightMatchEdges, rightToLeftMatchEdges);
//while there is an augmenting Path
while (freeVerticesOnRight.Count > 0)
{
var visited = new HashSet<T>();
var path = new HashSet<MatchEdge<T>>();
foreach (var vertex in freeVerticesOnRight)
{
var currentPath = Dfs(graph,
leftToRightMatchEdges, rightToLeftMatchEdges, vertex, default, visited, true);
if (currentPath != null) Union(path, currentPath);
}
Xor(matches, path, leftToRightMatchEdges, rightToLeftMatchEdges);
freeVerticesOnRight = Bfs(graph, partitions, leftToRightMatchEdges, rightToLeftMatchEdges);
}
return matches;
}
/// <summary>
/// Returns list of free vertices on right if there is an augmenting Path from left to right.
/// An augmenting path is a path which starts from a free vertex
/// and ends at a free vertex via UnMatched (left -> right) and Matched (right -> left) edges alternatively.
/// </summary>
private List<T> Bfs(IGraph<T> graph,
Dictionary<int, List<T>> partitions,
Dictionary<T, T> leftToRightMatchEdges, Dictionary<T, T> rightToLeftMatchEdges)
{
var queue = new Queue<T>();
var visited = new HashSet<T>();
var freeVerticesOnRight = new List<T>();
foreach (var vertex in partitions[1])
//if this left vertex is free
if (!leftToRightMatchEdges.ContainsKey(vertex) && !visited.Contains(vertex))
{
queue.Enqueue(vertex);
while (queue.Count > 0)
{
var current = queue.Dequeue();
visited.Add(vertex);
//unmatched edges left to right
foreach (var leftToRightEdge in graph.GetVertex(current).Edges)
{
if (visited.Contains(leftToRightEdge.TargetVertexKey)) continue;
//checking if this right vertex is free
if (!rightToLeftMatchEdges.ContainsKey(leftToRightEdge.TargetVertex.Key))
freeVerticesOnRight.Add(leftToRightEdge.TargetVertex.Key);
else
foreach (var rightToLeftEdge in leftToRightEdge.TargetVertex.Edges)
//matched edge right to left
if (leftToRightMatchEdges.ContainsKey(rightToLeftEdge.TargetVertexKey)
&& !visited.Contains(rightToLeftEdge.TargetVertexKey))
queue.Enqueue(rightToLeftEdge.TargetVertexKey);
visited.Add(leftToRightEdge.TargetVertexKey);
}
}
}
return freeVerticesOnRight;
}
/// <summary>
/// Find an augmenting path that start from a given free vertex on right and ending
/// at a free vertex on left, via Matched (right -> left) and UnMatched (left -> right) edges alternatively.
/// Return the matching edges along that path.
/// </summary>
private HashSet<MatchEdge<T>> Dfs(IGraph<T> graph,
Dictionary<T, T> leftToRightMatchEdges,
Dictionary<T, T> rightToLeftMatchEdges,
T current,
T previous,
HashSet<T> visited,
bool currentIsRight)
{
var currentIsLeft = !currentIsRight;
if (visited.Contains(current)) return null;
//free vertex on left found!
if (currentIsLeft && !leftToRightMatchEdges.ContainsKey(current))
{
visited.Add(current);
return new HashSet<MatchEdge<T>> { new(current, previous) };
}
//right to left should be unmatched edges
if (currentIsRight && !rightToLeftMatchEdges.ContainsKey(current))
foreach (var edge in graph.GetVertex(current).Edges)
{
var result = Dfs(graph, leftToRightMatchEdges, rightToLeftMatchEdges, edge.TargetVertexKey, current,
visited, !currentIsRight);
if (result != null)
{
result.Add(new MatchEdge<T>(edge.TargetVertexKey, current));
visited.Add(current);
return result;
}
}
//left to right should be matched edges
if (currentIsLeft && leftToRightMatchEdges.ContainsKey(current))
foreach (var edge in graph.GetVertex(current).Edges)
{
var result = Dfs(graph, leftToRightMatchEdges, rightToLeftMatchEdges, edge.TargetVertexKey, current,
visited, !currentIsRight);
if (result != null)
{
result.Add(new MatchEdge<T>(current, edge.TargetVertexKey));
visited.Add(current);
return result;
}
}
return null;
}
private void Union(HashSet<MatchEdge<T>> paths, HashSet<MatchEdge<T>> path)
{
foreach (var item in path)
if (!paths.Contains(item))
paths.Add(item);
}
private void Xor(HashSet<MatchEdge<T>> matches, HashSet<MatchEdge<T>> paths,
Dictionary<T, T> leftToRightMatchEdges, Dictionary<T, T> rightToLeftMatchEdges)
{
foreach (var item in paths)
if (matches.Contains(item))
{
matches.Remove(item);
leftToRightMatchEdges.Remove(item.Source);
rightToLeftMatchEdges.Remove(item.Target);
}
else
{
matches.Add(item);
leftToRightMatchEdges.Add(item.Source, item.Target);
rightToLeftMatchEdges.Add(item.Target, item.Source);
}
}
}