Python implementation of the Hungarian algorithm

 This algorithm mainly solves the problem of the maximum pairing number of two disjoint two sets. If there are two independent sets A, B, which can be matched when certain conditions are met in AB, but there may be more than one match for each element, then how to match so that the match between AB is maximized.

# 编写配置函数,其中used列表用来记录B是否被占用,这个在每次对A发现的时候需要清空
# match列表表示B与A中的匹配
# link表示A,B匹配的条件,满足返回真,失败返回FALSE
def find(index_item_A) -> bool:
    for index_item_B in range(len(B)):
        if not used[index_item_B] and link(A[index_item_A],B[index_item_B]):
           used[index_item_B] = True
           if match[index_item_B] == -1 or find(match[index_item_B]):
                match[index_item_B] = index_item_A
                return True
    return False

if __name__ == "__main__":
   count = 0
   #这里的count就是最大的那个匹配数目
   match = [-1 for i in range(len(B))]
   #这里初始化为-1,其含义是A中的与B匹配的下坐标之外,注意不能是0,最终的匹配在这里呈现
   for index in range(len(A)):
       used = [0 for i in range(len(B))]
       if find(index):
          count += 1
    print(count)

 

Published 42 original articles · praised 4 · 10,000+ views

Guess you like

Origin blog.csdn.net/wangyhwyh753/article/details/105538700