from cs4102lib import Graph, Queue def bfs0(graph, start): parent = {} color = {} for v in graph: color[v] = "white" pending = Queue() parent[start] = None color[start] = "gray" pending.add(start) while len(pending) > 0: v = pending.remove() alist = graph.get_adjlist(v) for w in alist: if color[w] == "white": color[w] = "gray" pending.add(w) parent[w] = v elif color[w] != "white" and parent[v] != w: print "cycle", v, w, color[w] color[v] = "black" return parent def bfs1(graph, start): # store this 3-tuple for each node: (parent, discovery, dist) # NOTE: for now this code is MISSING code to store these things nodeinfo = {} color = {} for v in graph: color[v] = "white" pending = Queue() color[start] = "gray" pending.add(start) ctr = 1 nodeinfo[start] = (None,1,0) # Hmm, what should be here? while len(pending) > 0: v = pending.remove() alist = graph.get_adjlist(v) for w in alist: if color[w] == "white": color[w] = "gray" pending.add(w) ctr = ctr + 1 parentinfo = nodeinfo[v] # (p, ctr, d) parentdist = parentinfo[2] # d nodeinfo[w] = (v,ctr, parentdist+1) color[v] = "black" return nodeinfo def main(): g1 = { "a": ["b", "f", "g"], "b": ["a", "c", "d", "e"], "c": ["b", "e"], "d": ["b", "e", "f"], "e": ["b", "c", "d", "f", "g"], "f": ["a", "d", "e"], "g": ["a", "e"], "h":[] } # print g1 gr1 = Graph(g1) print gr1 par = bfs0(gr1,"a") print "bfs0 return data:", par ninfo = bfs1(gr1,"a") #print "bfs1 return data:", ninfo ## Some code to test/explore the Graph object ## print len(gr1) ## print "Adj to d:", gr1.get_adjlist("d") ## print "Adj to h:", gr1.get_adjlist("h") ## print "Adj to x:", gr1.get_adjlist("x") ## ## print "a adj b? ", gr1.is_adjacent("a", "b") ## print "a adj d? ", gr1.is_adjacent("a", "d") ## print "a adj x? ", gr1.is_adjacent("a", "x") ## ## for v in gr1: ## print "vertex:", v, " alist:", gr1.get_adjlist(v) ## Some code to test/explore the Queue object ## l = [ 7, 9, 3, -1 ] ## q1 = Queue(l) ## print l ## print len(q1) ## q1.add(20) ## print "About to remove", q1.front() ## print q1.remove() ## print q1 ## print q1.remove() ## print len(q1) ## print q1 main()