![]() |
VOOZH | about |
Given a grid of m boys and n girls, where grid[i][j] = 1 represents that ith boy can invite girl jth girl to party. Each boy can invite only one girl and each girl can accept only one invitation. Find the most invitations that can be accepted.
Example:
Input: grid = {{1,1,1},
{1,0,1},
{0,0,1}}
Output: 3
Explanation: The invitations can be sent as follows:
=> 1st boy invites the 2nd girl.
=> 2nd boy invites the 1st girl.
=> 3rd boy invites the 3rd girl.Input: grid = {{1,0,1,0},
{1,0,0,0},
{0,0,1,0},
{1,1,1,0}}
Output: 3
Explanation: The invitations can be sent as follows:
=> 1st boy invites the 3rd girl.
=> 2nd boy invites the 1st girl.
=> 3rd boy invites no one.
=> 4th boy invites the 2nd girl.
Approach:
The solution uses the concept of maximum bipartite matching. We have to iterating over each boy and trying to find a girl that he can invite. If a boy finds a girl who hasn’t been invited yet, he invites her. If the girl has already been invited by another boy, then we recursively check if there is another girl that the other boy can invite. If yes, then the current boy invites the girl, and the other boy invites the other girl. This process is repeated until all boys have been checked.
The key idea here is to use depth-first search (DFS), we can efficiently backtrack and find alternative matches if a certain path doesn’t lead to a solution. This will makes sure that we find the maximum possible number of matches.
Steps-by-step approach:
Below are the implementation of the above approach:
The maximum possible number of accepted invitations is: 3
Time complexity: O(m * n), where m is the number of boys and n is the number of girls.
Auxiliary Space: O(n)