简体   繁体   English

DFS,在无向图中找到圆

[英]DFS , finding circle in undirected graph

This is my approach to deal with this problem. 这是我解决这个问题的方法。 But it seems this doesn't work as I expected. 但这似乎不符合我的预期。 What's wrong? 怎么了?

def dfs(graph, start, visited = None): '''find if there is a circle in the graph, if there is ,return True''' if visited == None: visited = set() visited.add(start) for next in graph[start]: if next in visited: return True else: dfs(graph, next, visited) return False

Since it is a Undirected graph, you have to take care of parent of current node, suppose you go from node 1 to node 2, then while traversing the edges of node 2 you will again find node 1 and it has already been visited so the answer will return true, ie cycle exists, but it might not be the case, so you need to add another parameter to check if adjacent node is not the parent of current node. 由于它是一个无向图,因此您必须照顾当前节点的父节点,假设您从节点1转到节点2,然后遍历节点2的边缘时,您将再次找到节点1并且已经对其进行了访问,因此答案将返回true,即存在循环,但事实并非如此,因此您需要添加另一个参数来检查相邻节点是否不是当前节点的父节点。 Here the parent node refers to the immediate predecessor of current node in the DFS Traversal. 此处,父节点是指DFS遍历中当前节点的直接前任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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