-
Notifications
You must be signed in to change notification settings - Fork 119
/
bfs.py
63 lines (54 loc) · 1.37 KB
/
bfs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from graph import *
from collections import deque
class BFSResults:
def __init__(self):
self.level = dict()
self.parent = dict()
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
def print_path(g, s, v):
if v == s:
print "path:", s,
elif r.parent[v] == None:
print "No path"
else:
print_path(g, s, r.parent[v])
print "-> "+v,
if __name__ == '__main__':
g = ALDirectedGraph()
g.add_edge('r', 's')
g.add_edge('r', 'v')
g.add_edge('s', 'r')
g.add_edge('s', 'w')
g.add_edge('t', 'w')
g.add_edge('t', 'x')
g.add_edge('t', 'u')
g.add_edge('u', 't')
g.add_edge('u', 'x')
g.add_edge('u', 'y')
g.add_edge('v', 'r')
g.add_edge('w', 's')
g.add_edge('w', 't')
g.add_edge('w', 'x')
g.add_edge('x', 'w')
g.add_edge('x', 't')
g.add_edge('x', 'u')
g.add_edge('x', 'y')
g.add_edge('y', 'x')
g.add_edge('y', 'u')
r = bfs(g, 'v')
print 'level:', r.level
print 'parent: ', r.parent
print_path(g, 'v', 'u')