Maximum Bipartite Matching
Last Updated :
01 Jun, 2023
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matchings for a given Bipartite Graph.
Why do we care?
There are many real world problems that can be formed as Bipartite Matching. For example, consider the following problem:
“There are M job applicants and N jobs. Each applicant has a subset of jobs that he/she is interested in. Each job opening can only accept one applicant and a job applicant can be appointed for only one job. Find an assignment of jobs to applicants in such that as many applicants as possible get jobs.”

We strongly recommend to read the following post first. “Ford-Fulkerson Algorithm for Maximum Flow Problem”
Maximum Bipartite Matching and Max Flow Problem :
Maximum Bipartite Matching (MBP) problem can be solved by converting it into a flow network (See this video to know how did we arrive this conclusion). Following are the steps.

1) Build a Flow Network : There must be a source and sink in a flow network. So we add a source and add edges from source to all applicants. Similarly, add edges from all jobs to sink. The capacity of every edge is marked as 1 unit.

2) Find the maximum flow: We use Ford-Fulkerson algorithm to find the maximum flow in the flow network built in step 1. The maximum flow is actually the MBP we are looking for.
How to implement the above approach?
Let us first define input and output forms. Input is in the form of Edmonds matrix which is a 2D array ‘bpGraph[M][N]’ with M rows (for M job applicants) and N columns (for N jobs). The value bpGraph[i][j] is 1 if i’th applicant is interested in j’th job, otherwise 0.
Output is number maximum number of people that can get jobs.
A simple way to implement this is to create a matrix that represents adjacency matrix representation of a directed graph with M+N+2 vertices. Call the fordFulkerson() for the matrix. This implementation requires O((M+N)*(M+N)) extra space.
Extra space can be reduced and code can be simplified using the fact that the graph is bipartite and capacity of every edge is either 0 or 1. The idea is to use DFS traversal to find a job for an applicant (similar to augmenting path in Ford-Fulkerson). We call bpm() for every applicant, bpm() is the DFS based function that tries all possibilities to assign a job to the applicant.
In bpm(), we one by one try all jobs that an applicant ‘u’ is interested in until we find a job, or all jobs are tried without luck. For every job we try, we do following.
If a job is not assigned to anybody, we simply assign it to the applicant and return true. If a job is assigned to somebody else say x, then we recursively check whether x can be assigned some other job. To make sure that x doesn’t get the same job again, we mark the job ‘v’ as seen before we make recursive call for x. If x can get other job, we change the applicant for job ‘v’ and return true. We use an array maxR[0..N-1] that stores the applicants assigned to different jobs.
If bmp() returns true, then it means that there is an augmenting path in flow network and 1 unit of flow is added to the result in maxBPM().
Implementation:
C++
#include <iostream>
#include <string.h>
using namespace std;
#define M 6
#define N 6
bool bpm(bool bpGraph[M][N], int u,
bool seen[], int matchR[])
{
for (int v = 0; v < N; v++)
{
if (bpGraph[u][v] && !seen[v])
{
seen[v] = true;
if (matchR[v] < 0 || bpm(bpGraph, matchR[v],
seen, matchR))
{
matchR[v] = u;
return true;
}
}
}
return false;
}
int maxBPM(bool bpGraph[M][N])
{
int matchR[N];
memset(matchR, -1, sizeof(matchR));
int result = 0;
for (int u = 0; u < M; u++)
{
bool seen[N];
memset(seen, 0, sizeof(seen));
if (bpm(bpGraph, u, seen, matchR))
result++;
}
return result;
}
int main()
{
bool bpGraph[M][N] = {{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}};
cout << "Maximum number of applicants that can get job is "
<< maxBPM(bpGraph);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static final int M = 6;
static final int N = 6;
boolean bpm(boolean bpGraph[][], int u,
boolean seen[], int matchR[])
{
for (int v = 0; v < N; v++)
{
if (bpGraph[u][v] && !seen[v])
{
seen[v] = true;
if (matchR[v] < 0 || bpm(bpGraph, matchR[v],
seen, matchR))
{
matchR[v] = u;
return true;
}
}
}
return false;
}
int maxBPM(boolean bpGraph[][])
{
int matchR[] = new int[N];
for(int i = 0; i < N; ++i)
matchR[i] = -1;
int result = 0;
for (int u = 0; u < M; u++)
{
boolean seen[] =new boolean[N] ;
for(int i = 0; i < N; ++i)
seen[i] = false;
if (bpm(bpGraph, u, seen, matchR))
result++;
}
return result;
}
public static void main (String[] args)
throws java.lang.Exception
{
boolean bpGraph[][] = new boolean[][]{
{false, true, true,
false, false, false},
{true, false, false,
true, false, false},
{false, false, true,
false, false, false},
{false, false, true,
true, false, false},
{false, false, false,
false, false, false},
{false, false, false,
false, false, true}};
GFG m = new GFG();
System.out.println( "Maximum number of applicants that can"+
" get job is "+m.maxBPM(bpGraph));
}
}
|
Python3
class GFG:
def __init__(self,graph):
self.graph = graph
self.ppl = len(graph)
self.jobs = len(graph[0])
def bpm(self, u, matchR, seen):
for v in range(self.jobs):
if self.graph[u][v] and seen[v] == False:
seen[v] = True
if matchR[v] == -1 or self.bpm(matchR[v],
matchR, seen):
matchR[v] = u
return True
return False
def maxBPM(self):
matchR = [-1] * self.jobs
result = 0
for i in range(self.ppl):
seen = [False] * self.jobs
if self.bpm(i, matchR, seen):
result += 1
return result
bpGraph =[[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]]
g = GFG(bpGraph)
print ("Maximum number of applicants that can get job is %d " % g.maxBPM())
|
C#
using System;
class GFG
{
static int M = 6;
static int N = 6;
bool bpm(bool [,]bpGraph, int u,
bool []seen, int []matchR)
{
for (int v = 0; v < N; v++)
{
if (bpGraph[u, v] && !seen[v])
{
seen[v] = true;
if (matchR[v] < 0 || bpm(bpGraph, matchR[v],
seen, matchR))
{
matchR[v] = u;
return true;
}
}
}
return false;
}
int maxBPM(bool [,]bpGraph)
{
int []matchR = new int[N];
for(int i = 0; i < N; ++i)
matchR[i] = -1;
int result = 0;
for (int u = 0; u < M; u++)
{
bool []seen = new bool[N] ;
for(int i = 0; i < N; ++i)
seen[i] = false;
if (bpm(bpGraph, u, seen, matchR))
result++;
}
return result;
}
public static void Main ()
{
bool [,]bpGraph = new bool[,]
{{false, true, true,
false, false, false},
{true, false, false,
true, false, false},
{false, false, true,
false, false, false},
{false, false, true,
true, false, false},
{false, false, false,
false, false, false},
{false, false, false,
false, false, true}};
GFG m = new GFG();
Console.Write( "Maximum number of applicants that can"+
" get job is "+m.maxBPM(bpGraph));
}
}
|
PHP
<?php
$M = 6;
$N = 6;
function bpm($bpGraph, $u, &$seen, &$matchR)
{
global $N;
for ($v = 0; $v < $N; $v++)
{
if ($bpGraph[$u][$v] && !$seen[$v])
{
$seen[$v] = true;
if ($matchR[$v] < 0 || bpm($bpGraph, $matchR[$v],
$seen, $matchR))
{
$matchR[$v] = $u;
return true;
}
}
}
return false;
}
function maxBPM($bpGraph)
{
global $N,$M;
$matchR = array_fill(0, $N, -1);
$result = 0;
for ($u = 0; $u < $M; $u++)
{
$seen=array_fill(0, $N, false);
if (bpm($bpGraph, $u, $seen, $matchR))
$result++;
}
return $result;
}
$bpGraph = array(array(0, 1, 1, 0, 0, 0),
array(1, 0, 0, 1, 0, 0),
array(0, 0, 1, 0, 0, 0),
array(0, 0, 1, 1, 0, 0),
array(0, 0, 0, 0, 0, 0),
array(0, 0, 0, 0, 0, 1));
echo "Maximum number of applicants that can get job is ".maxBPM($bpGraph);
?>
|
Javascript
<script>
let M = 6;
let N = 6;
function bpm(bpGraph, u, seen, matchR)
{
for (let v = 0; v < N; v++)
{
if (bpGraph[u][v] && !seen[v])
{
seen[v] = true;
if (matchR[v] < 0 || bpm(bpGraph, matchR[v],
seen, matchR))
{
matchR[v] = u;
return true;
}
}
}
return false;
}
function maxBPM(bpGraph)
{
let matchR = new Array(N);
for(let i = 0; i < N; ++i)
matchR[i] = -1;
let result = 0;
for (let u = 0; u < M; u++)
{
let seen =new Array(N);
for(let i = 0; i < N; ++i)
seen[i] = false;
if (bpm(bpGraph, u, seen, matchR))
result++;
}
return result;
}
let bpGraph = [
[false, true, true,
false, false, false],
[true, false, false,
true, false, false],
[false, false, true,
false, false, false],
[false, false, true,
true, false, false],
[false, false, false,
false, false, false],
[false, false, false,
false, false, true]];
document.write( "Maximum number of applicants that can"+
" get job is "+ maxBPM(bpGraph));
</script>
|
Output
Maximum number of applicants that can get job is 5
Time Complexity: O(V*E)
The time complexity of the above algorithm is O(V*E) where V is the number of vertices in the graph and E is the number of edges. The algorithm iterates over each vertex in the graph and then performs a DFS on the corresponding edges to find the maximum bipartite matching.
Space Complexity: O(V + E)
The space complexity of this algorithm is O(V + E) as it uses a two-dimensional boolean array to store the graph and an array to store the maximum matching.
You may like to see below also:
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)
Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)
Similar Reads
Graph Algorithms
Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
3 min read
Introduction to Graph Data Structure
Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
15+ min read
Graph and its representations
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
12 min read
Types of Graphs with Examples
A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
9 min read
Basic Properties of a Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
4 min read
Applications, Advantages and Disadvantages of Graph
Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
7 min read
Transpose graph
Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
9 min read
Difference Between Graph and Tree
Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. What is Graph?A graph data structure is a collection o
2 min read
BFS and DFS on Graph
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Traversal (BFS) starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list containing t
15+ min read
Depth First Search or DFS for a Graph
In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
15+ min read
Applications, Advantages and Disadvantages of Depth First Search (DFS)
Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
4 min read
Applications, Advantages and Disadvantages of Breadth First Search (BFS)
We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
4 min read
Iterative Depth First Traversal of Graph
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array. Example: Input: n = 4, e = 6 0
15+ min read
BFS for Disconnected Graph
In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
14 min read
Transitive Closure of a Graph using DFS
Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transit
8 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS st
2 min read
Cycle in a Graph
Detect Cycle in a Directed Graph
Given the root of a Directed graph , The task is to check whether the graph contains a cycle or not. Examples: Input: V = 4, E = 6 Output: Yes Explanation: The diagram clearly shows a cycle 0 -> 2 -> 0 Input: V = 4, E = 4 Output: No Explanation: The diagram clearly shows no cycle. [Expected Ap
14 min read
Detect cycle in an undirected graph
Given an undirected graph, the task is to check if there is a cycle in the given graph. Examples: Input: V = 4, E = 4 Output: Yes Explanation: The diagram clearly shows a cycle 0 to 2 to 1 to 0 Input: V = 4, E = 3 Output: No Explanation: There is no cycle in the given graph. Using Breadth First Sear
9 min read
Detect Cycle in a directed graph using colors
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. Example: Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: Yes Explanation: This dia
11 min read
Detect a negative cycle in a Graph | (Bellman Ford)
Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directe
15+ min read
Cycles of length n in an undirected and connected graph
Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
10 min read
Detecting negative cycle using Floyd Warshall
We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative. Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some adva
12 min read
Clone a Directed Acyclic Graph
A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
12 min read