迭代式图连通分量计数代码调试问题求助
图的连通分量计数迭代实现问题排查
问题背景
我正在学习图论,在实现图的连通分量计数时遇到困难。由于对递归掌握不熟练,我优先尝试编写迭代版本的实现。
初始代码及错误表现
最初的代码如下:
graph = { 0: [8, 1, 5], 1: [0], 5: [0, 8], 8: [0, 5], 2: [3, 4], 3: [2, 4], 4: [3, 2] } # return -> count of 2 def connected_components_count(graph): visited = set() stack = [] count = 0 for node in graph: if node not in visited: stack.append(node) visited.add(node) while len(stack) != 0: current = stack.pop() for neighbor in graph[current]: if neighbor not in visited: stack.append(neighbor) visited.add(neighbor) else: count += 1 return count
该代码针对示例图返回的计数为5,而非正确的2,我不清楚问题所在。
代码调整及后续疑惑
之后我调整了计数位置,将count +=1移到DFS遍历完成后,代码如下:
def connected_components_count(graph): visited = set() stack = [] count = 0 for node in graph: if node not in visited: stack.append(node) visited.add(node) while len(stack) != 0: current = stack.pop() for neighbor in graph[current]: if neighbor not in visited: stack.append(neighbor) visited.add(neighbor) count += 1 return count
调整后部分测试用例通过,但在如下测试用例中出现问题:
graph = { 2: [3, 1], 3: [2, 1], 1: [2, 3] } # -> return count 2
我认为该图只有1个连通分量,但测试用例要求返回2,对此感到疑惑。最终我发现该测试用例中存在一个隐藏节点,这才是计数为2的原因,感谢大家的帮助!
内容的提问来源于stack exchange,提问作者user11846775
相关产品推荐
相关产品推荐

