Depth First Search In Python to print nodes of Graph

Untitled document (1)
Graph

Graph

Shown above is a simple graph. Let’s define the characteristic of the graph:

  • This is a connected graph. Meaning, you can travel from anywhere to anywhere in this graph.  Read further here
  • This is an undirected graph. That simply means we don’t have any direction sense to the arrow connecting two nodes
  • This is an unweighted graph which is a different way of saying all the edges carry equal weight

Adjacency List

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a vertex in the graph. Read the wiki page here.

graph = {'A' : set(['G','B']),
'B' : set(['C','D','A']),
'C' : set(['F','D','B']),
'D' : set(['B','C']),
'E' : set(['F']),
'F' : set(['E','C']),
'G' : set(['A']),
}
print graph
##Output should be {'A': set(['B', 'G']), 'C': set(['B', 'D', 'F']),
## 'B': set(['A', 'C', 'D']), 'E': set(['F']), 'D': set(['C', 'B']),
## 'G': set(['A']), 'F': set(['C', 'E'])}
view raw graph_dict.py hosted with ❤ by GitHub

Our graph is now being represented in python dictionary using set

Print Nodes of Graph

We will now transverse the graph in depth-first fashion and try to print all the elements of the graph. Let’s say we start from A, we explore all the immediate neighbors before backtracking and then turn back when there is no further nodes.

def depth_first_search(graph, start_node):
visited_neighbours = set() #Keep track of the node we have visited like breadcrumbs to know the path
neighbours = [start_node] #list to store the neighbors. We will start with neigbors of void, the start node
while (len(neighbours) != 0): #All the elements will be transversed by the time we have this list size as zero
neighbour = neighbours.pop() #pop will take out randomly any one element and deletes from the list
if neighbour not in visited_neighbours:
visited_neighbours.add(neighbour)
new_prospected_neighbours = graph[neighbour]
#Need to remove neighbours which are already visted
new_neighbours = new_prospected_neighbours visited_neighbours
neighbours.extend(new_neighbours)
return visited_neighbours
depth_first_search(graph, 'A')
#output: {'A', 'B', 'C', 'D', 'E', 'F', 'G'}

 


Further Reading

MIT Video Lecture

If you liked this article and would like one such blog to land in your inbox every week, consider subscribing to our newsletter: https://skillcaptain.substack.com

Leave a Reply

Up ↑

%d bloggers like this: