forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.py
74 lines (64 loc) · 1.78 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
64
65
66
67
68
69
70
71
72
73
74
# breadth first search.
#a key-value pair represent a vertex and all it's outward edges.
adjacent = {}
#stores the list of vertex.
Vertex = []
# a key-value pair represents a vertex and its level.
# level of the root node is zero.
level = {}
# a key-value pair represents a vertex and its parent.
parent = {}
def initalizeVertex():
n = int(input('Enter the no. of vertices.\n'))
print("Enter the vertexes.")
for i in range(n):
vertex = input()
Vertex.append(vertex)
adjacent[vertex] = []
def initalizeUndirectedEdges():
n = int(input("Enter the no. of edges.\n"))
print("Enter the space seperated edges.")
for i in range(n):
a,b = input().split()
adjacent[a].append(b)
adjacent[b].append(a)
def initalizeDirectedEdges():
n = int(input("Enter the no. of edges.\n"))
print("Enter the space seperated edges.")
for i in range(n):
a,b = input().split()
adjacent[a].append(b)
def showVertex():
print('The vertexes are: ')
print(Vertex)
print('\n')
def showEdges():
print('The dictionary of edges are: ')
print(adjacent)
print('\n')
def bfs():
frontier = []
neighbour = []
start = input('Enter the first node.\n')
level[start] = 0
parent[start] = None
level_no = 1
frontier.append(start)
while len(frontier):
neighbour = []
for u in frontier:
for v in adjacent[u]:
if v not in level.keys():
level[v] = level_no
parent[v] = u
neighbour.append(v)
frontier = neighbour.copy()
level_no +=1
# program starts here.
initalizeVertex()
initalizeUndirectedEdges()
#showVertex()
#showEdges()
print('Implementing BFS.')
bfs()
print(level)