def __init__(self, G): self._marked = [False for i in range(G.V())] self._id = [-1 for i in range(G.V())] self._count = 0 # run DFS once on the reverse Graph! dfs = DFOrder(G.reverse()) # run DFS again on original Graph using reverse post order for v in dfs.reversePost(): if not self._marked[v]: self._dfs(G, v) self._count += 1
def __init__(self, G): "sorts the vertices of G in reverse DFS postorder" self._order = [] # determine whether G is a digraph or edge-weighted digraph if isinstance(G, Digraph): finder = DC(G) else: finder = EdgeWeightedDC(G) assert not finder.hasCycle(), "graph is not acyclic" dfs = DFOrder(G) self._order = dfs.reversePost()
def __init__(self, G): dfs = DFOrder(G) reverse_post = dfs.reversePost() target = reverse_post[-1] for v in reverse_post: if v != target: index = reverse_post.index(v) self._marked = [False for _ in range(G.V())] self._dfs(G, v) next = reverse_post[index+1] if not self._marked[next]: # v is not connected to the next vertex print "no Hamiltonian cycle" return print "Hamiltonian cycle:", reverse_post
def __init__(self, G): self._all_marked_lists = [] dc = DC(G) if dc.hasCycle(): # digraph with cycle for v in range(G.V()): self._marked = [False for _ in range(G.V())] self._dfs(G, v) self._all_marked_lists.append(self._marked) # done running DFS on vertices; find intersection of all marked lists all_lists = [[i for i in range(G.V()) if alist[i] is True] for alist in self._all_marked_lists] final = set(all_lists[0]) for s in all_lists[1:]: ss = set(s) final = final.intersection(ss) if not final: print "no vertex is reachable from all other vertices" else: for i in final: print i else: # DAG # only the target vertex is a candidate for being reachable dfs = DFOrder(G) reverse_post = dfs.reversePost() target = reverse_post[-1] for v in reverse_post: if v != target: self._marked = [False for _ in range(G.V())] self._dfs(G, v) self._all_marked_lists.append(set(self._marked)) # done running DFS on vertices; target must be in all marked lists for markedList in self._all_marked_lists: if target not in markedList: print "no vertex is reachable from all other vertices" return print target