Python:通过DFS查找二部图
我试图转换DFS程序来检查图是否是二部图。我希望遍历该路径并将访问的节点发送到不同的子集,只要它们不相邻。例如: 如果路径如下所示:1->2->3->4->5 两个子集应如下所示:Python:通过DFS查找二部图,python,graph,depth-first-search,adjacency-matrix,bipartite,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 visi
[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
在执行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.
请注意,我创建了一个集而不是一个列表,因为它可以更快地检查集的成员身份。如何表示图形,以及使用什么参数调用
dfs
?作为邻接矩阵“1”:([“2”]),
其中“1”是顶点,与“2”相邻如果有一个能正确设置所有空集的helper函数的包装器就好了。当然,但是原始的DFS代码也没有这样的功能,所以看起来不必要。看起来真的很好,你能指导我如何使用邻接矩阵将其打印到实际结果中吗?例如:graph={“1”:([“2”,“4”)],“2”:([“3”)],“3”:([“4”)],“4”:([“3”,1”)]}
是否需要检查递归调用的返回值,如果递归调用返回False,则立即返回False?