8000 Merge pull request #41 from anish03/bfs · AllAlgorithms/python@7698ca1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7698ca1

Browse files
authored
Merge pull request #41 from anish03/bfs
Added python implementation for breadth first search
2 parents 02ffd4d + fbae67c commit 7698ca1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

graphs/breadth_first_search.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Breadth First Search
2+
3+
from collect 8000 ions import defaultdict
4+
5+
class Graph:
6+
def __init__(self):
7+
self.graph = defaultdict(list)
8+
9+
def add_edges(self,_from,_to):
10+
for t in _to:
11+
self.graph[_from].append(t)
12+
13+
def display(self):
14+
print self.graph
15+
16+
def bfs(self,graph,start):
17+
queue = [start]
18+
visited = []
19+
20+
while queue:
21+
a = queue.pop(0)
22+
if a not in visited:
23+
visited.append(a)
24+
for neighbor in graph[a]:
25+
queue.append(neighbor)
26+
print visited
27+
28+
def main():
29+
30+
G = Graph()
31+
G.add_edges(1,[2,7,8])
32+
G.add_edges(2,[3,6])
33+
G.add_edges(3,[4,5])
34+
G.add_edges(8,[9,12])
35+
G.add_edges(9,[10,11])
36+
G.display()
37+
G.bfs(G.graph,1)
38+
39+
if __name__ == '__main__':
40+
main()

0 commit comments

Comments
 (0)
0