A bipartite graph is a special kind of graph where the set of vertices can be divided into two distinct and independent subsets. In simple terms, no two vertices within the same subset are adjacent.
Imagine a scenario where you have two groups: Group A (representing jobs) and Group B (representing applicants). Each job is connected to the applicants that can take it. This forms a bipartite structure where:
Vertices from Group A only connect to vertices in Group B, exemplifying the bipartite property.
Jobs (Group A) A1 ----- A2 | | | | Applicants (Group B) B1 B2
Matching refers to a set of edges that do not share any vertices. Finding a maximum matching (largest matching possible) in a bipartite graph is a common problem. There are several algorithms to achieve this, notably the Hungarian Algorithm and the Hopcroft-Karp Algorithm.
Consider the following bipartite graph:
Connections:
J1 -- A | \ | \ J2 -- B | \ | \ J3 -- C
Here’s a simple sketch in Java demonstrating the DFS and BFS approach to solve a matching problem in a bipartite graph:
import java.util.*; public class BipartiteMatching { static final int MAX = 100; static int[][] graph = new int[MAX][MAX]; static boolean[] visited; static int[] matchR; // DFS to find an augmenting path static boolean bpm(int u) { for (int v = 0; v < graph[0].length; v++) { if (graph[u][v] == 1 && !visited[v]) { visited[v] = true; if (matchR[v] == -1 || bpm(matchR[v])) { matchR[v] = u; return true; } } } return false; } public static int maxBPM() { matchR = new int[graph[0].length]; Arrays.fill(matchR, -1); int result = 0; for (int u = 0; u < graph.length; u++) { visited = new boolean[graph[0].length]; if (bpm(u)) { result++; } } return result; } public static void main(String[] args) { // Example graph initialization graph[0][0] = 1; graph[0][1] = 1; // J1 with A, B graph[1][1] = 1; graph[1][2] = 1; // J2 with B, C graph[2][2] = 1; // J3 with C System.out.println("Maximum number of applicants that can get jobs: " + maxBPM()); } }
graph[u][v] = 1
indicates a connection.The Hopcroft-Karp algorithm runs in O(E√V) time, making it efficient for large bipartite graphs. With E
being the number of edges and V
the number of vertices, this method remains practical for competitive programming and technical interviews.
By understanding the core principles of bipartite graphs and matching problems, you can better prepare yourself for advanced graph-related interview questions in Java.
08/12/2024 | DSA
16/11/2024 | DSA
13/10/2024 | DSA
15/11/2024 | DSA
06/12/2024 | DSA
08/12/2024 | DSA
13/10/2024 | DSA
16/11/2024 | DSA
23/09/2024 | DSA
06/12/2024 | DSA
16/11/2024 | DSA
23/09/2024 | DSA