You are on page 1of 1

21131A4410 | LOKESH DUDDUKURI

WEEK – 12

AIM: Implement Depth First Search


DESCRIPTION:
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data
structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in
the case of a graph) and explores as far as possible along each branch before backtracking.

PROGRAM:
graph = {}
n = int(input("Enter number of Nodes: "))
for i in range(n):
key = input("Enter the parent Node: ")
value = list(map(str,input("Enter the child Nodes").split()))
graph[key] = value

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,end=" ")
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph,
neighbour)

# Driver Code
OUTPUT:
Enter number of Nodes: 7
Enter the parent Node: 5
Enter the child Nodes3 7
Enter the parent Node: 3
Enter the child Nodes2 4
Enter the parent Node: 7
Enter the child Nodes8
Enter the parent Node: 2
Enter the child Nodes
Enter the parent Node: 4
Enter the child Nodes9
Enter the parent Node: 8
Enter the child Nodes
Enter the parent Node: 9
Enter the child Nodes
Following is the Depth-First Search
5 3 2 4 9 7 8

You might also like