There are m boys and n girls in a class attending an upcoming party.
You are given an m x n integer matrix grid, where grid[i][j] equals 0
or 1. If grid[i][j] == 1, then that means the ith boy can invite the
jth girl to the party. A boy can invite at mostone girl , and a girl can accept at most one invitation from a boy.
Return themaximum possible number of accepted invitations.
Input: grid =[[1,1,1],[1,0,1],[0,0,1]]Output: 3Explanation: The invitations are sent as follows:- The 1st boy invites the 2nd girl.- The 2nd boy invites the 1st girl.- The 3rd boy invites the 3rd girl.
Example 2:
1
2
3
4
5
6
7
8
9
10
Input: grid =[[1,0,1,0],[1,0,0,0],[0,0,1,0],[1,1,1,0]]Output: 3Explanation: The invitations are sent as follows:-The 1st boy invites the 3rd girl.-The 2nd boy invites the 1st girl.-The 3rd boy invites no one.-The 4th boy invites the 2nd girl.
The problem is about finding the maximum number of unique boy-girl pairs such that each boy invites at most one girl and each girl accepts at most one invitation. This is a classic bipartite matching problem, where boys and girls form two sets, and an edge exists if a boy can invite a girl. We use DFS to find augmenting paths and maximize the number of matches.
classSolution {
publicintmaximumInvitations(int[][] grid) {
int m = grid.length, n = grid[0].length, ans = 0;
int[] match =newint[n];
Arrays.fill(match, -1);
for (int u = 0; u < m; u++) {
boolean[] vis =newboolean[n];
if (dfs(u, grid, match, vis)) ans++;
}
return ans;
}
privatebooleandfs(int u, int[][] grid, int[] match, boolean[] vis) {
for (int v = 0; v < grid[0].length; v++) {
if (grid[u][v]== 1 &&!vis[v]) {
vis[v]=true;
if (match[v]==-1 || dfs(match[v], grid, match, vis)) {
match[v]= u;
returntrue;
}
}
}
returnfalse;
}
}
classSolution {
funmaximumInvitations(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
val match = IntArray(n) { -1 }
fundfs(u: Int, vis: BooleanArray): Boolean {
for (v in0 until n) {
if (grid[u][v] ==1&& !vis[v]) {
vis[v] = trueif (match[v] == -1|| dfs(match[v], vis)) {
match[v] = u
returntrue }
}
}
returnfalse }
var ans = 0for (u in0 until m) {
val vis = BooleanArray(n)
if (dfs(u, vis)) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defmaximumInvitations(self, grid: list[list[int]]) -> int:
m, n = len(grid), len(grid[0])
match= [-1] * n
defdfs(u: int, vis: list[bool]) -> bool:
for v in range(n):
if grid[u][v] andnot vis[v]:
vis[v] =Trueifmatch[v] ==-1or dfs(match[v], vis):
match[v] = u
returnTruereturnFalse ans =0for u in range(m):
vis = [False] * n
if dfs(u, vis):
ans +=1return ans
⏰ Time complexity: O(m * n) per boy, so total O(m * n^2) – for each boy, we may visit all girls, and for each girl, we may traverse up to all boys in the worst case.
🧺 Space complexity: O(m + n) – for the match array and visited array per DFS call.