Skip to content

Commit 4c01bdf

Browse files
authored
BFS & DFS
Initial File
1 parent 8ab0da5 commit 4c01bdf

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

BFS & DFS

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#Breadth First Search [BFS]
2+
3+
queue = [] #Initialize a queue
4+
visited=[]
5+
def bfs(graph, node):
6+
queue.append(node)
7+
visited.append(node)
8+
while queue:
9+
curr = queue.pop(0)
10+
print (curr, end = " ")
11+
12+
for neighbour in graph[curr]:
13+
if neighbour not in visited:
14+
queue.append(neighbour)
15+
visited.append(neighbour)
16+
17+
18+
19+
20+
21+
#Depth First Search [DFS]
22+
23+
visited = [] # Set to keep track of visited nodes.
24+
25+
def dfs(graph, node):
26+
if node not in visited:
27+
print (node)
28+
visited.append(node)
29+
for neighbour in graph[node]:
30+
dfs(graph, neighbour)

0 commit comments

Comments
 (0)