递归路径查找错误

时间:2014-07-11 16:22:38

标签: python python-3.x recursion

我正在进行一项练习,其中两点之间有一组连接(即12是1和2之间的连接等)。我决定递归地处理这个方法,以便系统地检查每个路径,并在找到一个命中每个节点并以一个节点开始和结束时返回。

然而,在调试这个时,似乎当我将adjMatrix进一步传递到递归时,它也在编辑上层并导致它不再搜索,因为它返回到树上。我认为当我设置newMatrix = adjMatrix时会有所帮助,但我并不确定。

def checkio(teleports_string):
    #return any route from 1 to 1 over all points
    firstnode, secondnode, size = 0, 0, 8

    #Makes the adjacency matrix
    adjMatrix = [[0 for i in range(size)] for j in range(size)]

    for x in teleports_string:
        #Assigns Variables
        if firstnode == 0 and x != ",":
            #print("Node1:" + x)
            firstnode = x
        elif secondnode == 0 and x != ",":
            #print("Node2:" + x)
            secondnode = x
        #Marks connections
        if firstnode != 0 and secondnode != 0:
            adjMatrix[int(firstnode) - 1][int(secondnode) - 1] = 1
            adjMatrix[int(secondnode) - 1][int(firstnode) - 1] = 1
            firstnode, secondnode = 0, 0
    print(adjMatrix)

    return findPath(adjMatrix, 1, "1")


def findPath(adjMatrix, currentnode, currentpath):
    if isFinished(currentpath):
        return currentpath

    for x in range(0, 8):
        if adjMatrix[currentnode - 1][x] == 1:
            print(currentpath + "+" + str(x+1))
            newMatrix = adjMatrix
            newMatrix[currentnode - 1][x] = 0
            newMatrix[x][currentnode - 1] = 0
            temp = currentpath
            temp += str(x+1)
            newpath = findPath(newMatrix, x+1,temp)
            print(newpath)
            if isFinished(newpath):
                 print ("Returning: " + newpath)
                 return newpath
    return ""


def isFinished(currentpath):
    #Checks if node 1 is hit at least twice and each other node is hit at least once
    if currentpath == "":
        return False

    for i in range(1, 9):
        if i == 1 and currentpath.count(str(i)) < 2:
            return False
        elif currentpath.count(str(i)) < 1:
            return False
    #Checks if it starts and ends with 1
    if not currentpath.startswith(str(1)) or not currentpath.endswith(str(1)):
        return False
    return True

#This part is using only for self-testing
if __name__ == "__main__":
    def check_solution(func, teleports_str):
        route = func(teleports_str)
        teleports_map = [tuple(sorted([int(x), int(y)])) for x, y in teleports_str.split(",")]
        if route[0] != '1' or route[-1] != '1':
            print("The path must start and end at 1")
            return False
        ch_route = route[0]
        for i in range(len(route) - 1):
            teleport = tuple(sorted([int(route[i]), int(route[i + 1])]))
            if not teleport in teleports_map:
                print("No way from {0} to {1}".format(route[i], route[i + 1]))
                return False
            teleports_map.remove(teleport)
            ch_route += route[i + 1]
        for s in range(1, 9):
            if not str(s) in ch_route:
                print("You forgot about {0}".format(s))
                return False
        return True

    assert check_solution(checkio, "13,14,23,25,34,35,47,56,58,76,68"), "Fourth"

1 个答案:

答案 0 :(得分:1)

该行

newMatrix = adjMatrix

仅创建对列表的另一个引用。您需要实际创建 new 列表对象。由于这是一个矩阵,请对内容执行此操作:

newMatrix = [row[:] for row in adjMatrix]

这将创建嵌套列表的新副本列表。