0% found this document useful (0 votes)
11 views3 pages

Practical No1

The document provides an implementation of Depth-First Search (DFS) and Breadth-First Search (BFS) algorithms using a sample graph. It defines a graph structure and includes functions to perform DFS and BFS traversals, printing the nodes in the order they are visited. Example usages of both algorithms are demonstrated with the starting node 'A'.

Uploaded by

204044.astcwit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Practical No1

The document provides an implementation of Depth-First Search (DFS) and Breadth-First Search (BFS) algorithms using a sample graph. It defines a graph structure and includes functions to perform DFS and BFS traversals, printing the nodes in the order they are visited. Example usages of both algorithms are demonstrated with the starting node 'A'.

Uploaded by

204044.astcwit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Practical no.

01
DFS AND BFS:
graph = {

'A': ['B', 'C'],

'B': ['D', 'E'],

'C': ['F'],

'D': [],

'E': ['F'],

'F': []

def dfs(graph, node, visited=None):

if visited is None:

visited = set()

if node not in visited:

print(node, end=" ")

visited.add(node)

for neighbor in graph[node]:

dfs(graph, neighbor, visited)

# Example usage

print("DFS Traversal:")
dfs(graph, 'A')

from collections import deque

def bfs(graph, start):

visited = set()

queue = deque([start])

while queue:

node = queue.popleft()

if node not in visited:

print(node, end=" ")

visited.add(node)

queue.extend(graph[node])

# Example usage

print("\nBFS Traversal:")

bfs(graph, 'A')

OUTPUT:

You might also like