-
Notifications
You must be signed in to change notification settings - Fork 119
/
bfs_1.py
52 lines (47 loc) · 1.11 KB
/
bfs_1.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
from collections import deque
def bfs(graph, source):
color = {}
d = {}
p = {}
for node in graph:
color[node] = 0
d[node] = float('Inf')
p[node] = None
color[source] = 1
d[source] = 0
p[source] = None
actives = deque()
actives.append(source)
while len(actives):
u = actives.popleft()
for v in graph[u]:
if color[v] == 0:
color[v] = 1
d[v] = d[u] + 1
p[v] = u
actives.append(v)
color[u] = 2
return d, p
def print_path(graph, source, v, p):
if v == source:
print source
elif p[v] == None:
print "No Path"
else:
print_path(graph, source, p[v], p)
print v
def test():
graph = {
'v' : {'r'},
'r' : {'v', 's'},
's' : {'r', 'w'},
'w' : {'s', 'x', 't'},
'x' : {'w', 't', 'u', 'y'},
't' : {'w', 'x', 'u'},
'u' : {'t', 'x', 'y'},
'y' : {'x', 'u'}
}
d, p = bfs(graph, 'v')
print d, p
print_path(graph, 'v', 'u', p)
if __name__ == '__main__': test()