Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




PYTHON - DEPTH FIRST SEARCH CODE ITERATIVE




We will be seeing the Iterative way for implementing Depth First Search (DFS). Although there are various ways to write this Iterative code.


However, we will write the code little differently. So that you can corelate it with the Depth First Search (DFS) explanation.


In the Iterative code we will create the stack and maintain it ourselves.


DFS - Depth First Search code for Undirected Graph - Iterative approach


Example :



def insertVertex(vertex):
	vertices.append(vertex)

def constructAdjacencyList(vtx, adjcVertex):
	vtxIndex = vertices.index(vtx)
	adjacencyList.append([])
	adjacencyList[vtxIndex].append(adjcVertex)

def depthFirstSearch(source):
	sourceIndex = vertices.index(source)
	visited[sourceIndex] = True
	stack = []
	stack.append(source)
	print(source, end = " --> ")
	while (len(stack) != 0):
		source = stack[-1] # Peek operation
		sourceIndex = vertices.index(source)
		str = ""
		for iter in adjacencyList[sourceIndex]:
			str = iter
			i = vertices.index(str)
			if (visited[i] == False):
				stack.append(str)
				visited[i] = True
				print(str, end = " --> ")
				break
		if (stack[-1] != str):
			stack.pop()
	print("\b\b\b\b", end = "    \n")


V = 6
visited = [False]*V
adjacencyList = [[]]
vertices = []

# Insert Vertices

insertVertex("a")
insertVertex("b")
insertVertex("c")
insertVertex("d")
insertVertex("e")
insertVertex("f")

constructAdjacencyList("a", "c")
constructAdjacencyList("a", "d")

constructAdjacencyList("b", "d")
constructAdjacencyList("b" ,"e")
constructAdjacencyList("b" ,"c")

constructAdjacencyList("c", "a")
constructAdjacencyList("c", "b")
constructAdjacencyList("c", "e")

constructAdjacencyList("d", "a")
constructAdjacencyList("d" ,"b")
constructAdjacencyList("d", "e")
constructAdjacencyList("d", "f")

constructAdjacencyList("e", "b")
constructAdjacencyList("e", "c")
constructAdjacencyList("e", "d")
constructAdjacencyList("e", "f")

constructAdjacencyList("f", "d")
constructAdjacencyList("f", "e")

depthFirstSearch("a")



Output :



  a --> c --> b --> d --> e --> f

Code Explanation


We have implemented Depth First Search (DFS) on the below graph :

java_Collections

We can take various ways to navigate the graph using Depth First Search (DFS). Just remember our main intension is to visit all the vertices.


In this case we have covered the graph in the following path :


a --> c --> b --> d --> e --> f

Let us see how ?


Code Explanation for DFS - Depth First Search - Iterative :


Below code explains the methods :

  1. def constructAdjacencyList(vtx, adjcVertex)


  2. def insertVertex(vertex)


Almost the same we have discussed in BFS. You can skip it if you want to.



Click Here - To understand the details of the methods 'def constructAdjacencyList(vtx, adjcVertex)' and 'def insertVertex(vertex)'.


Let's list out, what all do we need to support Depth First Search Data Structure.

  1. We need a Linked List to store the vertices.
    java_Collections

  2. We need a doubly Linked List to store the adjacency linked list.
    java_Collections

  3. We need a Queue and an array to store its Levels.

  4. We need a boolean array to store the Vertices that are already visited.

Now, let us see the above code.


We have a Linked List to store the Vertices.


vertices

We also have a doubly Linked List to store the Adjacency List.


adjacencyList

Similarly, we have a stack defined inside the method depthFirstSearch(...).


stack

And, there is a boolean array to store the Vertices that are visited.


visited

So, the first thing we will do is, insert the Vertices to the vertices Linked List.


vertices = []

# Insert Vertices

insertVertex("a")
insertVertex("b")
insertVertex("c")
insertVertex("d")
insertVertex("e")
insertVertex("f")

Explanation of 'def insertVertex(vertex)' method


def insertVertex(vertex):
	vertices.append(vertex)

def insertVertex(vertex) is quite simple.


There is just one statement in it.


vertices.append(vertex)

It accepts String vertex as a parameter and adds it to the Linked List, vertices.

java_Collections

The next thing we will do is, create an Adjacency List to track the Adjacent Vertices.


Let us take the example of vertex a, to explain the creation of Adjacency List.


As we have seen, a has two adjacent vertices(i.e. c and d). And we have used the constructAdjacencyList(...) method to construct the Adjacency Matrix.


constructAdjacencyList("a", "c")
constructAdjacencyList("a", "d")

Note : Just remember, creating an Adjacency List above is same as creating an Edge. As the Adjacency List is actually a group of Edges.


Explanation of 'def constructAdjacencyList(vtx, adjcVertex)' method


def constructAdjacencyList(vtx, adjcVertex):
	vtxIndex = vertices.index(vtx)
	adjacencyList.append([])
	adjacencyList[vtxIndex].append(adjcVertex)

Although, the above method is explained in Adjacency List Code tutorial. I will give a brief explanation in this tutorial.


When a method call is made,

java_Collections

The variable vtx is assigned with value "a" and adjcVertex is assigned with "b".


Now, the first line,


vtxIndex = vertices.index(vtx)

Calculates the index/position of Vertex a. And as we can see the index a is 0.


Now, in the next line,


adjacencyList.append([])

We are initialising the first row of the 2D Linked List, adjacencyList.


But with what ?


We are initialising it with an Array [],


adjacencyList.append([])

So that the first row can hold the Adjacency List for vertex a.


a   ---   c ---> d

Similarly, the second row should hold the Adjacency List for vertex b and so on.


And in this iteration, our target is to find out the first row(To create an Adjacency List for vertex a) and insert vertex b to it.


And the below code does that.


adjacencyList[vtxIndex].append(adjcVertex)

We get the index of vertex a


vtxIndex = vertices.index(vtx)

As we know vtx is a.


Then add adjcVertex(That contains vertex c) to the 0th index of adjacencyList.


adjacencyList[0].append("c")

And following it we form the Adjacency List.


Now, we come across the most important method def depthFirstSearch(source) that performs the Depth First Search (DFS).


Explanation of 'def depthFirstSearch(source)' method


Example :



def depthFirstSearch(source):
	sourceIndex = vertices.index(source)
	visited[sourceIndex] = True
	stack = []
	stack.append(source)
	print(source, end = " --> ")
	while (len(stack) != 0):
		source = stack[-1] # Peek operation
		sourceIndex = vertices.index(source)
		str = ""
		for iter in adjacencyList[sourceIndex]:
			str = iter
			i = vertices.index(str)
			if (visited[i] == False):
				stack.append(str)
				visited[i] = True
				print(str, end = " --> ")
				break
		if (stack[-1] != str):
			stack.pop()
	print("\b\b\b\b", end = "    \n")



We have called the def depthFirstSearch(source) from the main method passing a as the parameter.


depthFirstSearch("a")

So, the first thing we will do is, take the index of a,


sourceIndex = vertices.index(source)

Now, if we see the List of vertices,

java_Collections

We can see that a lies in index 0.


Next, we mark a as visited,


visited[sourceIndex] = True

in the visited[] array,


visited[0] = True;
java_Collections


Then, we create the stack,


stack = []

And the immediate next thing we do is, push a to the stack.


stack.append(source)
java_Collections


Then we print the vertex a.


print("\b\b\b\b", end = "    \n")

Output :



  a -->

Next, we enter the while() loop that continues until the stack is not empty.


while (len(stack) != 0):
	source = stack[-1] # Peek operation
	sourceIndex = vertices.index(source)
	str = ""
	for iter in adjacencyList[sourceIndex]:
		str = iter
		i = vertices.index(str)
		if (visited[i] == False):
			stack.append(str)
			visited[i] = True
			print(str, end = " --> ")
			break
	if (stack[-1] != str):
		stack.pop()

In the while() loop, we take the top element(i.e. a) in the source variable.


source = stack[-1] # Peek operation

Note : Just remember, source = stack[-1] does not pop the top element from the stack. It just shows the top element of the stack.

The we take the index of the top element(0 is the index of a).


sourceIndex = vertices.index(source)

Then comes the for(...) loop, where we find the find the adjacent vertices of the top element(i.e. a).


for iter in adjacencyList[sourceIndex]:
	str = iter
	i = vertices.index(str)
	if (visited[i] == False):
		stack.append(str)
		visited[i] = True
		print(str, end = " --> ")
		break

The first statement of the for loop (i.e. The initialisation section of the loop),


iter

is where we get the Adjacent Vertices of vertex c in the iter.


Thinking How ?


Well ! The adjacencyList is a 2D Linked List that stores the adjacent vertices. And the trick is played in,


adjacencyList[sourceIndex]

As we have seen, the sourceIndex is 0 (Because the index of vertex a is 0).


And the iter variable of iter gets the adjacency list of vertex a in it.


iter variable of Iterator<String> iter, stores the Adjacency List of vertex a in it.So, iter has the elements c and d in it.


Now, str contains the first adjacent vertex c.


str = iter

Next, we find the index of vertex c,


i = vertices.index(str)

Now, if we see the List of vertices,

java_Collections

We can see that c lies in index 2.


So, we check if c is visited or not.


if (visited[i] == False):
	stack.append(str)
	visited[i] = True
	print(str, end = " --> ")
	break

Now, if we check the visited array,

java_Collections

We found that visited[2] = False and we get into the if statement.


So, we push c to the Queue.

java_Collections

And marked visited[2] = True,


visited[i] = True;

In the visited[] array,

java_Collections

then we break out of the for loop


break

After getting out of the for loop, we check if the value inside the str variable and the top element are equal or not.


if (stack[-1] != str):
	stack.pop()

In this case str has c inside it and the top element of the stack is also c.


So, we don't pop c out of the stack and continue with the while loop.


Note : The statement 'if (stack[-1] != str)' says when we reach a vertex whose adjacent vertices are already visited. The statement 'stack.append(str)' will never be executed. And, 'str' will have a value that is not equal to the top element of the stack.

Similarly, we repeat the same process until all the vertices are visited.

java_Collections
java_Collections

Now, let's visit the while() loop again.


The top element is f now,


source = stack[-1] # Peek operation

So, the value of source variable is f and


sourceIndex = vertices.index(source)

the value of sourceIndex variable would be 5.


Now, the adjacent vertices of f are d and e.


for iter in adjacencyList[sourceIndex]:

So, the variable str would contain d(Since, the adjacent vertices of f are d and e) in the first iteration and would be e in the second iteration.


str = iter
i = vertices.index(str)

And both e and d are visited. So, the lines under the if statement are never visited.


if (visited[i] == False):
	stack.append(str)
	visited[i] = True
	print(str, end = " --> ")
	break

So, the for loop completes. And the value of the variable str would be e.


So, after getting out of the for loop, we check if the value inside the str variable and the top element are equal or not.


if (stack[-1] != str):
	stack.pop()

In this case the top element is f and the value in str is e.


And the if (stack[-1] != str) condition matches and f is popped out of the queue.


stack.pop()
java_Collections


Continuing in the same way, all the elements are popped out of the Queue and the execution ends.