Depth first search generator

This is the standard iterative DFS code modified to yield the vertices visited, so you don't have to pass a function into the DFS routine to process them. Note that this code is not quite complete... you'll need to define the function neighbors (v) based on your graph representation.


To use this code, just do:

for v in DFS (G, start):
    process (v)

Personally, I think this is more natural than passing a function into a DFS routine.

A nice example application is the following function to tell whether the graph G is connected or not:

def is_connected (G):
    return len (list (DFS (G, G.vertices[0]))) == len (G.vertices)
def DFS (G, v):
    yield v
    visited = set ([v])
    S = neighbors (v)
    while S:
        w = S.pop()
	if w not in visited:
	    yield w
	    visited.add (w)
	    S.extend (neighbors (w))

code.activestate.com ↗