Maximum Number of Accepted Invitations Problem
Description
LeetCode Problem 1820.
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 i^th boy can invite the j^th girl to the party. A boy can invite at most one girl, and a girl can accept at most one invitation from a boy.
Return the maximum possible number of accepted invitations.
Example 1:
Input: grid = [[1,1,1],
[1,0,1],
[0,0,1]]
Output: 3
Explanation: The invitations are sent as follows:
- The 1^st boy invites the 2^nd girl.
- The 2^nd boy invites the 1^st girl.
- The 3^rd boy invites the 3^rd girl.
Example 2:
Input: grid = [[1,0,1,0],
[1,0,0,0],
[0,0,1,0],
[1,1,1,0]]
Output: 3
Explanation: The invitations are sent as follows:
-The 1^st boy invites the 3^rd girl.
-The 2^nd boy invites the 1^st girl.
-The 3^rd boy invites no one.
-The 4^th boy invites the 2^nd girl.
Constraints:
grid.length == mgrid[i].length == n1 <= m, n <= 200grid[i][j]is either0or1.
Solution
Approach: Bipartite Matching (Hungarian Algorithm)
Boys and girls form a bipartite graph, with an edge when grid[i][j] == 1. We need its maximum matching, which the Hungarian algorithm finds.
Take the boys one at a time. For boy i, try to find an augmenting path: go through each girl j he can invite who has not been visited in this round. Mark her visited; if she is free, or the boy she is currently matched to can switch to another girl (a recursive attempt), then match her to i. If the attempt succeeds, the matching grows by one. The visited marks are reset for each new boy.
The answer is the number of boys who got matched.
Complexity: O(m * m * n) in the worst case (each of the m boys triggers a search over at most m * n edges), O(n) extra space.
class Solution:
def maximumInvitations(self, grid: List[List[int]]) -> int:
def find(i):
for j, v in enumerate(grid[i]):
if v and j not in vis:
vis.add(j)
if match[j] == -1 or find(match[j]):
match[j] = i
return True
return False
m, n = len(grid), len(grid[0])
match = [-1] * n
ans = 0
for i in range(m):
vis = set()
ans += find(i)
return ans