Maximum Bipartite Matching

The bipartite matching is a set of edges in a graph is chosen in such a way, that no two edges in that set will share an endpoint. The maximum matching is matching the maximum number of edges.

When the maximum match is found, we cannot add another edge. If one edge is added to the maximum matched graph, it is no longer a matching. For a bipartite graph, there can be more than one maximum matching is possible.

Input and Output

Input:
0 1 1 0 0 0
1 0 0 1 0 0
0 0 1 0 0 0
0 0 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 1

Output:
Maximum number of applicants matching for job: 5

Algorithm

bipartiteMatch(u, visited, assign)

Input: Starting node, visited list to keep track, assign the list to assign node with another node.

Output − Returns true when a matching for vertex u is possible.

Begin
for all vertex v, which are adjacent with u, do
if v is not visited, then
mark v as visited
if v is not assigned, or bipartiteMatch(assign[v], visited, assign) is true, then
assign[v] := u
return true
done
return false
End

maxMatch(graph)

Input − The given graph.

Output − The maximum number of the match.

Begin
initially no vertex is assigned
count := 0
for all applicant u in M, do
make all node as unvisited
if bipartiteMatch(u, visited, assign), then
increase count by 1
done
End

Example

#include <iostream>
#define M 6
#define N 6
using namespace std;

bool bipartiteGraph[M][N] = {    //A graph with M applicant and N jobs
{0, 1, 1, 0, 0, 0},
{1, 0, 0, 1, 0, 0},
{0, 0, 1, 0, 0, 0},
{0, 0, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 1}
};

bool bipartiteMatch(int u, bool visited[], int assign[]) {
for (int v = 0; v < N; v++) {    //for all jobs 0 to N-1
if (bipartiteGraph[u][v] && !visited[v]) {    //when job v is not visited and u is interested
visited[v] = true;    //mark as job v is visited
//when v is not assigned or previously assigned
if (assign[v] < 0 || bipartiteMatch(assign[v], visited, assign)) {
assign[v] = u;    //assign job v to applicant u
return true;
}
}
}
return false;
}

int maxMatch() {
int assign[N];    //an array to track which job is assigned to which applicant
for(int i = 0; i<N; i++)
assign[i] = -1;    //initially set all jobs are available
int jobCount = 0;

for (int u = 0; u < M; u++) {    //for all applicants
bool visited[N];
for(int i = 0; i<N; i++)
visited[i] = false;    //initially no jobs are visited
if (bipartiteMatch(u, visited, assign))    //when u get a job
jobCount++;
}
return jobCount;
}

int main() {
cout << "Maximum number of applicants matching for job: " << maxMatch();
}

Output

Maximum number of applicants matching for job: 5

karthikeya Boyini

I love programming (: That's all I know

Updated on: 16-Jun-2020

7K+ Views