Suppose there are m boys and n girls, and m = n. There is a party incoming, and each boy has to go with a girl to that party. So, the boys invite all the girls and a girl can accept one invitation only. We have to find out the total number of invitations from the boys that the girls can accept. The input is given in a m x n matrix, where each cell position i, j denotes if the boy i has sent a letter to girl j. If a cell is 1 it means that an invitation has been sent, if it is 0 it means no invitation is sent.
So, if the input is like
then the output will be 3.
The output will be 3 if −
Girl 1 accepts boy 1's invitation.
Girl 2 accepts boy 3's invitation.
Girl 3 accepts boy 2's invitation.
(here index starts at 1)
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(grid): M, N = len(grid), len(grid) matching = [-1] * N def dfs(node, seen): for nei in range(N): if grid[node][nei] and not seen[nei]: seen[nei] = True if matching[nei] == -1 or dfs(matching[nei], seen): matching[nei] = node return True return False res = 0 for i in range(M): seen = [False] * N if dfs(i, seen): res += 1 return res print(solve([[1, 0, 0], [1, 0, 1], [1, 1, 0]]))
[[1, 0, 0], [1, 0, 1], [1, 1, 0]]