Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
28 views1 page

Dfs Py

The document provides two implementations of Depth-First Search (DFS) for traversing graphs: a recursive version and an iterative version. The recursive DFS function explores neighbors of a vertex and builds a path, while the iterative DFS uses a stack to achieve the same result. Example graphs and their traversal outputs are included for both methods.

Uploaded by

prasad mane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views1 page

Dfs Py

The document provides two implementations of Depth-First Search (DFS) for traversing graphs: a recursive version and an iterative version. The recursive DFS function explores neighbors of a vertex and builds a path, while the iterative DFS uses a stack to achieve the same result. Example graphs and their traversal outputs are included for both methods.

Uploaded by

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

def dfs_recursive(graph, vertex, path=[]):

path += [vertex]

for neighbor in graph[vertex]:


if neighbor not in path:
path = dfs_recursive(graph, neighbor, path)

return path

matrix = {'A': ['B', 'C'], 'B': ['D', 'E'],


'C': ['E'], 'D': ['G'], 'E': ['G'],
'G': ['H'], 'H': []}

print(dfs_recursive(matrix, 'A'))
# [1, 2, 4, 6, 7, 5, 3]

def dfs_iterative(graph, start):


stack, path = [start], []

while stack:
vertex = stack.pop()
if vertex in path:
continue
path.append(vertex)
for neighbor in graph[vertex]:
stack.append(neighbor)

return path

adjacency_matrix = {1: [2, 3], 2: [4, 5],


3: [5], 4: [6], 5: [6],
6: [7], 7: []}

print(dfs_iterative(adjacency_matrix, 1))
# [1, 3, 5, 6, 7, 2, 4]

You might also like