# Depth First Search

Example Code, heres Code of a Graph that we will use in our DFS Algorithm

``````
class Graph:

def __init__(self, Nodes, is_directed = False):
self.nodes = Nodes

self.is_directed = is_directed

for node in self.nodes:

if not self.is_directed:

def degree(self,node):
'''Total number of edges coming out a given node'''
return deg

for node in self.nodes:

def __getitem__(self, node):

"""retrives items from out Node/vertex"""

all_edges = [

("A","B"),("A","C"),("B","D"),("C","D"),("C","E"),("D","E")
]
nodes = ["A","B","C","D","E"]

graph1 = Graph(nodes)

for u,v in all_edges:

``````

Heres Depth First Search Algorithm

``````visited = []

def dfs(graph, node):

if node not in visited:

visited.append(node)

for neighbor in graph[node]:

dfs(graph,neighbor)

return visited

dfs(graph1, "A")

print("Nodes Visted: ", visited)
``````

Output:

``````A -> ['B', 'C']
B -> ['A', 'D']
C -> ['A', 'D', 'E']
D -> ['B', 'C', 'E']
E -> ['C', 'D']
Nodes Visted:  ['A', 'B', 'D', 'C', 'E']
``````