Skip to content

Commit cf3c107

Browse files
committed
added new BFS code
1 parent 7386f90 commit cf3c107

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

bfs.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
class Vertex:
2+
def __init__(self, n):
3+
self.name = n
4+
self.neighbors = list()
5+
6+
self.distance = 9999
7+
self.color = 'black'
8+
9+
def add_neighbor(self, v):
10+
if v not in self.neighbors:
11+
self.neighbors.append(v)
12+
self.neighbors.sort()
13+
14+
class Graph:
15+
vertices = {}
16+
17+
def add_vertex(self, vertex):
18+
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
19+
self.vertices[vertex.name] = vertex
20+
return True
21+
else:
22+
return False
23+
24+
def add_edge(self, u, v):
25+
if u in self.vertices and v in self.vertices:
26+
for key, value in self.vertices.items():
27+
if key == u:
28+
value.add_neighbor(v)
29+
if key == v:
30+
value.add_neighbor(u)
31+
return True
32+
else:
33+
return False
34+
35+
def print_graph(self):
36+
for key in sorted(list(self.vertices.keys())):
37+
print(key + str(self.vertices[key].neighbors) + " " + str(self.vertices[key].distance))
38+
39+
def bfs(self, vert):
40+
q = list()
41+
vert.distance = 0
42+
vert.color = 'red'
43+
for v in vert.neighbors:
44+
self.vertices[v].distance = vert.distance + 1
45+
q.append(v)
46+
47+
while len(q) > 0:
48+
u = q.pop(0)
49+
node_u = self.vertices[u]
50+
node_u.color = 'red'
51+
52+
for v in node_u.neighbors:
53+
node_v = self.vertices[v]
54+
if node_v.color == 'black':
55+
q.append(v)
56+
if node_v.distance > node_u.distance + 1:
57+
node_v.distance = node_u.distance + 1
58+
59+
g = Graph()
60+
a = Vertex('A')
61+
g.add_vertex(a)
62+
g.add_vertex(Vertex('B'))
63+
for i in range(ord('A'), ord('K')):
64+
g.add_vertex(Vertex(chr(i)))
65+
66+
edges = ['AB', 'AE', 'BF', 'CG', 'DE', 'DH', 'EH', 'FG', 'FI', 'FJ', 'GJ', 'HI']
67+
for edge in edges:
68+
g.add_edge(edge[:1], edge[1:])
69+
70+
g.bfs(a)
71+
g.print_graph()

0 commit comments

Comments
 (0)