{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

recitation11

# recitation11 - MIT OpenCourseWare http/ocw.mit.edu 6.006...

This preview shows pages 1–7. Sign up to view the full content.

MIT OpenCourseWare http://ocw.mit.edu 6.006 Introduction to Algorithms Spring 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms .

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
6.006 Recitation Build 2008.22
6.006 Proudly Presents Graph Traversal BFS DFS Topological Sorting

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Breadth-First Search a.k.a. BFS (not BFG) Fix your source Visit all the neighbors Then visit all the neighbors’ neighbors Then all the neighbors’ neighbors’ neighbors’ ... 1 2 3 5 4 7 8 6 9 10 11
BFS in Python: Design Use the graph module shown before, and Python’s deque Encapsulate traversal data in a class, return at the end of the traversal Implement traversal as stand-alone function 1 from graph import * 2 from collections import deque 3 4 class BFSResults: 5 def __init__(self): 6 self.level = dict() 7 self.parent = dict()

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 BFS in Python: Code def bfs(g, s): r = BFSResults() actives = deque() actives.append(s) r.parent[s] = None r.level[s] = 0 while len(actives): v = actives.popleft() for n in g.neighbors(v): if n not in r.parent: r.parent[n] = v r.level[n] = r.level[v] + 1 actives.append(n) return r
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 20

recitation11 - MIT OpenCourseWare http/ocw.mit.edu 6.006...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online