匈牙利算法

时间:2017-03-19 11:33:03

标签: python algorithm python-3.4 hungarian-algorithm

我在Python 3.4中从头开始编写匈牙利语算法,并且遇到了关于覆盖零的最佳行的问题。

我从其维基百科页面中获取了算法的定义,这是用于查找覆盖所有零的最小行的代码:

def minZeroLines(matrix):

    markMatrix = [] #first for marked rows, second for marked columns

    for row in range(len(matrix)):
        markMatrix.append([])
        for col in range(len(matrix)):
            markMatrix[row].append("")

    for row in range(len(matrix)):
        for col in range(len(matrix)):
            if matrix[row][col] == 0 and ("*" not in [i[col] for i in markMatrix] and "*" not in markMatrix[row]):
                markMatrix[row][col] = "*"

    print(markMatrix)

    rowColMark = [[],[]] #1st rows, 2nd cols

    for i in range(len(matrix)):
        rowColMark[0].append("")
        rowColMark[1].append("")

    for row in range(len(markMatrix)):
        if "*" not in markMatrix[row]:
            rowColMark[0][row] = "x"

    print(rowColMark)

    for row in range(len(markMatrix)):
        if rowColMark[0][row] == "x":
            for col in range(len(matrix)):
                if matrix[row][col] == 0:
                    rowColMark[1][col] = "x"
                    for row2 in range(len(markMatrix)):
                        if matrix[row2][col] == 0 and markMatrix[row2][col] == "*":
                            rowColMark[0][row2] = "x"

    print(rowColMark)

    lineList = []

    for col in range(len(rowColMark[1])):
        if rowColMark[1][col] == "x":
            lineList.append("c"+str(col))

    for row in range(len(rowColMark[0])):
        if rowColMark[0][row] != "x":
            lineList.append("r"+str(row))

    print(rowColMark)
    print(lineList)
    return lineList

问题在于,当我通过它运行下面的矩阵时,在初始分配零期间,作为寻找覆盖它们的最小线的第一步,选择矩阵[1] [1]处的零。这导致函数稍后标记所有行,这意味着它们不会被排列,即使行矩阵[1]应该是明确的。

matrix = [[0, 0, 16, 16, 16, 16, 16],
      [0, 0, 0, 0, 0, 0, 0],
      [0, 0, 16, 16, 16, 16, 16],
      [0, 0, 16, 16, 16, 16, 16],
      [0, 0, 16, 16, 16, 16, 16],
      [0, 0, 16, 16, 16, 16, 16],
      [0, 0, 16, 16, 16, 16, 16]]

这是导致问题的部分:

for row in range(len(matrix)):
    for col in range(len(matrix)):
        if matrix[row][col] == 0 and ("*" not in [i[col] for i in markMatrix] and "*" not in markMatrix[row]):
            markMatrix[row][col] = "*"

我认为必须有一些我错过的条件会阻止分配零,但这在我看过的描述和其他地方都没有详细说明。谁知道我做错了什么?

0 个答案:

没有答案
相关问题