comparison Graph.py @ 7:69e5977417b3

Section 2.4, exercise 5, create an is_connected() method for the Graph. Also implement breadth-first search.
author Brian Neal <bgneal@gmail.com>
date Sun, 02 Dec 2012 21:51:51 -0600
parents 950a34c7e26b
children 1defe6fcf9d3
comparison
equal deleted inserted replaced
6:950a34c7e26b 7:69e5977417b3
189 189
190 for i in range(n / 2): 190 for i in range(n / 2):
191 v = vs2[i] 191 v = vs2[i]
192 w = vs2[i + n / 2] 192 w = vs2[i + n / 2]
193 self.add_edge(Edge(v, w)) 193 self.add_edge(Edge(v, w))
194
195 def bfs(self, start, visit_func=None):
196 """Perform a breadth first search starting at node start.
197
198 The function visit_func, if supplied, is invoked on each node.
199
200 """
201 # Mark all vertices as unvisited
202 vs = self.vertices()
203 for v in vs:
204 v.visited = False
205
206 # Create a work queue consisting initially of the starting node
207 queue = [start]
208
209 while queue:
210 # retrieve first item from the queue
211 v = queue.pop(0)
212
213 if v.visited:
214 continue # Skip this one if we've seen it before
215
216 # Mark it as visited and invoke user's function on it
217 v.visited = True
218 if visit_func:
219 visit_func(v)
220
221 # Add the adjacent neigbors to the node to the queue
222 queue.extend(self.out_vertices(v))
223
224 def is_connected(self):
225 """Returns True if the graph is connected (there is a path from every
226 node to every other node) and False otherwise.
227
228 """
229 vs = self.vertices()
230 if len(vs):
231 self.bfs(vs[0])
232 # See if all nodes have been visited
233 for v in vs:
234 if not v.visited:
235 return False
236 return True
237
238 return False # Graph is empty
194 239
195 240
196 def main(script, *args): 241 def main(script, *args):
197 import pprint 242 import pprint
198 243
233 x = Vertex('x') 278 x = Vertex('x')
234 g.add_vertex(x) 279 g.add_vertex(x)
235 g.add_all_edges() 280 g.add_all_edges()
236 pprint.pprint(g) 281 pprint.pprint(g)
237 282
283 print "g is connected?", g.is_connected()
284 edges = g.out_edges(v)
285 for e in edges:
286 g.remove_edge(e)
287 pprint.pprint(g)
288 print "g is connected?", g.is_connected()
289
290 # Isolate v and check is_connected() again
291
238 292
239 if __name__ == '__main__': 293 if __name__ == '__main__':
240 import sys 294 import sys
241 main(*sys.argv) 295 main(*sys.argv)