-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_bfs.py
64 lines (48 loc) · 1.06 KB
/
graph_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
64
def change(n):
if colour[n-1]=='w':
colour[n-1]='b'
q.append(n)
def source(n):
if colour[n-1]=='b':
colour[n-1]='r'
'''for n in d:
for j in d[n]:
pre[j-1]=n
dis[j-1]+=1'''
from collections import defaultdict
l=[]
n=int(input("enter no.of nodes"))
m=int(input("enter no.of edges"))
for i in range(m):
x=input("enter edge")
x=x.replace(",","")
l.append(list(x))
s=int(input("enter source vertex"))
bfs=[]
d=defaultdict(list)
for i in l:
d[int(i[0])].append(int(i[1]))
d[int(i[1])].append(int(i[0]))
q=[]
colour=['w']*n
pre=[None]*n
dis=[0]*n
change(s)
for i in d[s]:
change(i)
for i in d:
change(i)
for j in d[i]:
change(j)
print(q)
while(len(q)!=0):
element=q.pop(0)
bfs.append(element)
source(element)
for i in d[element]:
if colour[i-1]!='r':
pre[i-1]=element
dis[i-1]+=1
print(pre)
print(colour)
print(dis)