Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 7698ca1

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

File tree

Expand file treeCollapse file tree

1 file changed

+40
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+40
-0
lines changed

‎graphs/breadth_first_search.py

Copy file name to clipboard
+40Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Breadth First Search
2+
3+
from collections 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)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.