Program to find out the number of accepted invitations in Python

PythonServer Side ProgrammingProgramming

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

100
101
110

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 −

  • Define a function dfs() . This will take node, seen
    • for nei in range 0 to N, do
      • if grid[node][nei] is non-zero and seen[nei] is False, then
        • seen[nei] := True
        • if matching[nei] is same as -1 or dfs(matching[nei], seen) is True, then
          • matching[nei] := node
          • return True
    • return False
  • M:= row count of grid
  • N := column count of grid
  • matching := a list of size N containing value -1
  • res := 0
  • for i in range 0 to M, do
    • seen := a list of size N containing value False
    • if dfs(i, seen) is True, then
      • return res
  • return res

Example

Let us see the following implementation to get better understanding −

def solve(grid):
   M, N = len(grid), len(grid[0])
   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]]))

Input

[[1, 0, 0], [1, 0, 1], [1, 1, 0]]

Output

3
raja
Published on 07-Oct-2021 12:21:32
Advertisements