查找图的所有连通分量时递归深度过大,如何优化现有实现代码
问题原因
原实现采用递归版本的深度优先搜索(DFS)遍历节点,Python默认递归深度上限约为1000,当图中单个连通分量的遍历深度超过该阈值时就会触发递归深度超限错误。另外原实现用列表存储已访问节点,成员查询的时间复杂度为O(n),大图场景下性能损耗明显。
优化方案
使用迭代版DFS或者广度优先搜索(BFS)替换递归逻辑即可,两种方案都不受递归深度限制,时间复杂度和原实现一致为O(V+E)(V为节点总数,E为边总数)。把已访问节点存储结构从列表替换为集合后,成员查询效率可提升到O(1),进一步提升处理性能。
优化后代码
BFS实现(推荐,遍历顺序更稳定)
from collections import deque def get_connected_components(adj_matrix): adj_dict = get_dict(adj_matrix) components = [] visited = set() for node in adj_dict.keys(): if node not in visited: current_component = [] # 队列实现BFS逻辑 queue = deque([node]) visited.add(node) while queue: current = queue.popleft() current_component.append(current) for neighbor in adj_dict[current]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) components.append(current_component) return components
迭代版DFS实现
def get_connected_components(adj_matrix): adj_dict = get_dict(adj_matrix) components = [] visited = set() for node in adj_dict.keys(): if node not in visited: current_component = [] # 栈实现迭代版DFS逻辑 stack = [node] visited.add(node) while stack: current = stack.pop() current_component.append(current) for neighbor in adj_dict[current]: if neighbor not in visited: visited.add(neighbor) stack.append(neighbor) components.append(current_component) return components
内容的提问来源于stack exchange,提问作者JohnPers
相关产品推荐
相关产品推荐

