def DFS (G, start = unspecified): ''' This is a generator that yields vertices from the vertex set of graph $G$ in the order they are encountered in a depth-first search of $G$ starting from the vertex \code{start} (if specified) or from some arbitrary vertex in \code {G.vertices} if \code {start} is not specified. ''' if start is unspecified: start = arbitraryElementOf (G.vertices) neighbors = graph.adjacencyLists (G) yield start visited = set ([start]) stack = neighbors [start] while stack: w = stack.pop() if w not in visited: yield w visited.add (w) stack.extend (neighbors [w])
def Prim (G, root = unspecified): ''' Returns the edges of a minimum-weight spanning tree of $G$, starting from the vertex \code {root} (if specified). ''' if root is unspecified: root = arbitraryElementOf(G.vertices) key = {} Pi = {} adj = graph.adjacencyLists(G) for u in G.vertices: key [u] = Infinity Pi [u] = None key [root] = 0 Q = PriorityQueue (G.vertices) while Q: u = Q.extract_min() for v in adj[u]: if v in Q and G.weight ( (u, v) ) < key [v]: Pi [v] = u key[v] = G.weight ( (u, v) ) return [(v, Pi[v]) for v in G.vertices if v is not root]
def BFS (G, start = unspecified): ''' This is a generator that yields the vertices of $G$ in the order they are encountered during a breadth-first search of $G$ starting at the vertex \code {start} (if specified), or starting at some arbitrary vertex in \code {G.vertices} if not specified. ''' if start is unspecified: start = arbitraryElementOf (G.vertices) neighbors = graph.adjacencyLists (G) reached = Queue([]) searched = set ([]) reached.add (start) while not reached.empty(): v = reached.remove() yield v for w in neighbors [v]: if w not in searched and w not in reached: reached.add (w) searched.add (v)