0% found this document useful (0 votes)
112 views

DFS & BFS Implementation in Python

The document describes implementing depth-first search (DFS) and breadth-first search (BFS) algorithms in Python. It provides sample code to perform DFS and BFS on a graph with nodes 5, 3, 7, 2, 4, and 8. The DFS code uses recursion to traverse the graph depth-first, while the BFS code uses a queue to traverse the graph breadth-first.

Uploaded by

ayushstwt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

DFS & BFS Implementation in Python

The document describes implementing depth-first search (DFS) and breadth-first search (BFS) algorithms in Python. It provides sample code to perform DFS and BFS on a graph with nodes 5, 3, 7, 2, 4, and 8. The DFS code uses recursion to traverse the graph depth-first, while the BFS code uses a queue to traverse the graph breadth-first.

Uploaded by

ayushstwt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

DFS Implementation in Python

Now, knowing the algorithm to apply the Depth-First Search implementation in


python, we will see how the source code of the program works.

Consider the following graph which is implemented in the code below:

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
BFS Implementation in Python
Now, we will see how the source code of the program for implementing breadth first
search in python.

Consider the following graph which is implemented in the code below:

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

You might also like