def __init__(self, g: DiGraph): self.id = [None]*(g.V+1) self.marked = [False]*(g.V+1) self.curr_component = 0 self.num_of_components = 0 tsort = TopologicalSort(g.reverse()) postorder = tsort.getPostorder() self.g = g for elem in postorder: if not self.marked[elem]: self.dfs(g, elem) self.curr_component += 1 self.num_of_components += 1
def dfs(self, g: DiGraph, i: int): self.onStack[i] = True self.marked[i] = True for node in g.close(i): if self.hasCycle: # short circuit if cycle return elif not self.marked[i]: self.edgeTo[node] = i self.dfs(g, node) elif self.onStack[node]: # There is a cycle cycle = [] init = i while init != node: cycle.append(init) init = self.edgeTo[init] cycle.append(node) return cycle self.onStack[i] = False
def dfs(self, g: DiGraph, v: int): self.marked[v] = True self.id[v] = self.curr_component for node in g.close(v): if not self.marked[node]: self.dfs(g, node)
def dfs(self, g: DiGraph, i: int): self.marked[i] = True for nodes in g.close(i): if not self.marked[nodes]: self.dfs(g, nodes) self.stack.append(i)