简体   繁体   中英

Python: Finding a bipartite graph by DFS

I'm trying to transform DFS programme to check if graph is bipartite. I want to go through the path and send visited nodes to different subsets as far as they aren't adjacent. For example:

if path would look like this: 1->2->3->4->5

Two subsets should look like this:

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

And here is DFS code:

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

Testing for bipartite-ness is done by "coloring" adjacent nodes with alternating colors as you perform DFS, and if any two wind up with the same "color" then the graph is not bipartite. You can do this by putting nodes into two different sets as you perform DFS as such:

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.

Note that I made visited a set instead of a list because it is faster to check for membership of a set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM