defDFS_visit(graph, start, time=-1): # initialize: done by init Node time += 1 start.d = time start.color = 1 for v in graph[start]: if v.color == 0: v.color = 1 v.p = start time = DFS_visit(graph, v, time) time += 1 start.f = time start.color = 2 return time
DFS_visit(G,nodes['I'])
for n in G.keys(): print(f"{n.value},{n.d},{n.f}")
classSolution: defcriticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: graph = self.convert_to_graph(connections) result = [] for u in graph.keys(): if u.color == 0: self.DFS_visit(graph, u, 0, result) return result
defDFS_visit(self, graph, u, t, result): u.color = 1 t += 1 u.st = t u.low = t for v in graph[u]: if v.color == 0: v.p = u t = self.DFS_visit(graph, v, t, result) u.low = min(u.low, v.low) if v.low > u.st: result.append([u.value, v.value]) elif v != u.p: u.low = min(u.low, v.st) u.color = 2 return t
defconvert_to_graph(self, connections): node_dict = {} graph = {} for u, v in connections: if u notin node_dict: node_dict[u] = Node(u) graph[node_dict[u]] = [] if v notin node_dict: node_dict[v] = Node(v) graph[node_dict[v]] = [] graph[node_dict[u]].append(node_dict[v]) graph[node_dict[v]].append(node_dict[u]) return graph
4.Topological Sort
拓扑排序是一种对有DAG的顶点进行线性排序的算法。这种排序满足以下条件:对于图中的每一条有向边 (u, v),顶点 u 在排序中总是位于顶点 v 的前面。换句话说,拓扑排序反映了图中顶点之间的依赖关系。