在无向图中返回顶点

时间:2015-05-04 05:40:32

标签: python algorithm graph undirected-graph

我试图在Python中提出一种贪婪算法,它在给定某个起始顶点的情况下返回无向图中的顶点。我知道DFS确定是否存在循环,但我试图实际返回形成循环的顶点。我使用邻接矩阵来表示以下图表:

adjacencyMatrix = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]

图示这是一个由单个周期组成的无向图。

我当前的思维过程是将我的起始索引设置为我遇到的第一个1(在这种情况下为adjacencyMatrix[0][1])。然后我会查看行的其余部分,看看是否有另一个1,因为这意味着我当前的顶点连接到该索引。但是,我不完全确定(a)这是正确的方法,(b)如何“移动”到下一个顶点。例如,如何导航嵌套的for循环以从adjacencyMatrix[0][1]顶点移动到adjacencyMatrix[0][2]顶点?我只是交换行和列索引吗?

修改 我想出的这个解决方案似乎适用于我试过的几张图:

def findCycle(matrix):
    visited = list()
    cycleNotFound = True
    row = 0
    col = 0
    startVertex = (0, 0)

    while cycleNotFound:

        # Only add a vertex if it has not already been visited
        if (matrix[row][col] == 1) and ((row, col) not in visited):
            # Set the startVertex when the first node is found
            if len(visited) == 0:
                startVertex = (row, col)

            # Add the current vertex and its counter part
            visited.append((row, col))
            visited.append((col, row))

            # If row and col are equal, infite loop will get created
            if row != col:
                row = col
                col = 0
            else:
                row += 1

        # If back at starting point, break look
        elif ((row, col) == startVertex) and (len(visited) > 1):
            cycleNotFound = False
            visited.append(startVertex)

        # Else, continue to look for unvisted neighbors
        else:
            col += 1

    return visited

if __name__ == "__main__":
    matrix = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]
    cycle = findCycle(matrix)
    index = 0
    # Print the vertices.  Only print even vertices to avoid duplicates.
    while (index < len(cycle)):
        print cycle[index]
        index += 2

它不是最优雅的解决方案,我确信需要进行一些重大的重构。

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

def findCycle(node):
    cycle = stack()
    if( DFS(node, cycle) ):
        return cycle
    return None

def DFS(node, cycle):
    cycle.append(node)
    mark node as visited
    foreach node.neighbors as neighbor:
        if neighbor already visited:
            return true
        else:
            if( DFS(neighbor, cycle) ) return true
    cycle.remove(node)
    return false