Extension of a Ford Fulkerson max flow problem using depth first search
Given an undirected bipartite graph, find the maximum matching between left & right halves. Each node in the Left half L
mapped to at most 1 node in R
. Similarly, each node in the Right Half R
is mapped to at most 1 node in L
Goal: maximize the number of matchings
Convert to a Max Flow / Min Cut problem by making a directed graph:
- Make all edges from
L
toR
directed with capacity1
A flow of1
corresponds to yes there's a matching and0
mean no matching
Since there's only 2 values, it could even be implemented as aboolean
- Add a Source
S
& create directed edges fromS
to every vertex in the left half with capacity1
- Add a Sink
T
& create directed edges from every vertex in the right half toT
with capacity1
- Use Ford-Fulkerson algorithm to find the max flow
- Graph is represented as an edge list
vertexCount
must be an accurate number of nodes in the graphgetStringVertexIdFromArrayIndex
allows conversion between the array indexes used by the actual algorithm & the human-readable names of the vertices. These are sequential with"S"
and"T"
being added at the endS
&T
are added to the end of the list of vertices withS
getting array indexvertexCount
andT
getting array indexvertexCount+1
int[] leftHalfVertices
contains the array indexes of the vertices in the left part of the bipartite graph- Similarly,
int[] rightHalfVertices
contains the vertices in the right half - These must be consecutive integers with the 1st number in
rightHalfVertices
being 1 greater than the last number inleftHalfVertices
- Use
addEdge()
method onBipartiteMatching
class to add new edges
The initial bipartie graph is undirected so undirected edges should only be added once. They are converted to directed edges when finding the max flow - Run
connectSourceToLeftHalf()
to modify the graph & add the source, thenconnectSinkToRightHalf()
to connect the sink - Run
fordFulkersonMaxFlow(source, sink)
to find the maximum matching
The code uses array indexes instead of nice human-readable Vertex names. Red numbers represent array indexes
All edge capacities are 1
but omitted here for clarity of the picture