Python:通过DFS查找二分图

时间:2018-05-17 17:37:20

标签: python graph depth-first-search adjacency-matrix bipartite

我试图转换DFS程序以检查图形是否为二分图。我想通过路径并将访问过的节点发送到不同的子集,只要它们不相邻。例如:

  

如果路径如下所示:1-> 2-> 3-> 4-> 5

两个子集应如下所示:

[1,3,5] [2,4]

这是DFS代码:

def dfs(x, node, visited):
if node not in visited:
    visited.append(node)
    for n in x[node]:
        dfs(x,n, visited)
return visited

1 个答案:

答案 0 :(得分:0)

测试二分法是通过"着色"当您执行DFS时,相邻节点具有交替的颜色,如果任何两个节点使用相同的颜色"颜色"然后图表不是二分图。您可以通过在执行DFS时将节点放入两个不同的集合来执行此操作:

def bipart(x, node, visited, set1, set2):
    if node in set2:                   # if a node has already been put into the other set, the graph is not bipartite
        return False
    if node not in visited:            # if we haven't seen this yet
        visited.add(node)              # mark it as visited
        set1.add(node)                 # put it in the first set
        for n in x[node]:              # for each neighbor
            bipart(x, n, set2, set1)   # put it into the other set
    return True                        # if we get here we have separated the graph into two sets where all the neighbors of a node in one set are in the other set.

请注意,我将visited设置为一个集合而不是列表,因为检查集合的成员资格会更快。