1) DFS Algorithm
Graph:
Order of Traversal: A B E F G C D
Python Code:
graph = {
'A' : ['B','C','D'],
'B' : ['E','F'],
'C' : ['F'],
'D' : [],
'E' : [],
'F' : ['G'],
'G' : []
} # Created a graph dictionary having 7 items as vertices
and its adjacent nodes.
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node):# Defines the DFS algorithm function with
visited,graph,node variables
if node not in visited:
print (node)# By the above if definition node is not visited
prints the node corresponds to it in set.
visited.add(node)
for neighbour in graph[node]:# Visits all the edges until all
nodes are finished.
dfs(visited, graph, neighbour)# Each of the neighbour
corresponds to the current node and the function is called again and
print the node in set.Then function returns.
# Driver Code
dfs(visited, graph, 'A')# function calls and pass the visited node to
set,then create the graph in form of dictionary as stars from A.That
is the arguments is being passed to function.
Output:
A
B
E
F
G
C
D
Applications:
Path finding between two vertices u and v.
Used for topological sorting.
In an unweighted graph it can create MST.
2) BFS Algorithm
Graph:
Order of Traversal: A B C D E F G H
Python Code:
graph = {
'A' : ['B','C','D'],
'B' : ['E','F'],
'C' : ['F'],
'D' : ['G'],
'E' : [],
'F' : ['H'],
'G' : [],
'H' : []
}# Created a graph dictionary having 7 items as vertices and its
adjacent nodes.
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node):# Defines the BFS algorithm function with
visited,graph,node variables
visited.append(node)
queue.append(node)# this checking and appending the starting node to
the list of visited and also in queue.
while queue:
s = queue.pop(0)
print (s , end=" ") # when the queue contains the node it popout
the node .
for neighbour in graph[s]:# Runs upto queue is empty
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)# if neighbour is not visited append the
neighbour to queue and ,make it as visited node.
# Driver Code
bfs(visited, graph, 'A')# The function arguments are the visited ,graph
and starts form the node A.
Output: A B C D E F G H
Applications:
Peer to peer network like bittorrent,it is used to find neighbouring node.
Search engine crawlers uses BFS.
In GPS navigation system.
3) Prim’s Algorithm
Graph:
Minimum Spanning Tree:
Python Code:
INF = 9999999 # Create an infinite vertices of graph.
V = 5 # Create an array for matrix of 5*5
G = [[0,10,15,0,0],
[10,0,20,5,8],
[15,20,0,12,6],
[0,5,12,0,13],
[0,8,6,13,0]] # Create an adjacency matrix of elements.
selected = [0, 0, 0, 0, 0]# creating an array of zeros to find the
vertex so that it will be true.
# set number of edge to 0.
no_edge = 0
selected[0] = True # Number of edges in MST will be always less than
vertices-1,so choose zeroth vertex and make it true.
# print for edge and weight.
print("Edge : Weight\n")
while (no_edge < V - 1):
minimum = INF
x = 0
y = 0# when while becomes true it assign these values.
for i in range(V):#Runs till the total number of vertex selected
as row manner.
if selected[i]:# Check vertex in selected array.
for j in range(V):#Runs till the total number of vertex
selected in column manner.
if ((not selected[j]) and G[i][j]):
# not in selected and there is an edge
if minimum > G[i][j]:# Check for condition.
minimum = G[i][j]# Take the edge as minimum
weight.
x = i
y = j# If element is not selected put these
values.
print(str(x) + "" + str(y) + ":" + str(G[x][y]))# Print the selecte
d edge.
selected[y] = True
no_edge += 1 # Take the y element in selected array and make it as
true and increment the number of edge to next.
Output:
Edge : Weight
0-1:10
1-3:5
1-4:8
4-2:6
Applications:
Travelling Salesman
Computer network
4) Kruskal’s Algorithm
Graph:
Minimum Spanning Tree:
Python Code:
from collections import defaultdict
class Graph: # Created the class for graph
def __init__(self, vertices): # Function to initialize
self.V = vertices # take as number of vertices
self.graph = [] # take the graph dictionary as initial
def addEdge(self, u, v, w):# Function to add edges to graph
self.graph.append([u, v, w]) # Append to graph each edge as
source,destination,weight respectively
def find(self, parent, i):# Function to find set of i
if parent[i] == i:
return i
return self.find(parent, parent[i])# Returns the set consisting
of element i.
def union(self, parent, rank, x, y):# Function to create union of x
& y with their rank.
xroot = self.find(parent, x)
yroot = self.find(parent, y)# Find and add the ranked variables
to root variables.
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot# Compare the ranks and put the small
one in the roots of higher.
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1 # if rank of both is same increment the
rank by one.
def KruskalMST(self): # Main function of Kruskal's algorithm.
result = []# Default result.
i = 0 # indexing element for the edges.
e = 0 # indexing element for result variable.
self.graph = sorted(self.graph, key=lambda item: item[2])
# Sort the weight of each edges in increasing order without changing
the orginal graph.
parent, rank = [], []
for node in range(self.V):#Loop for run upto number of vertices
parent.append(node)# Creating the set of V with adding
single elements.
rank.append(0)
while e < self.V-1:
# Check for condition up to number of vertices equal to vertices-1.
u, v, w = self.graph[i]
i += 1 # Take the smallest edge and increment index by one.
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e += 1
result.append([u, v, w]) # Find the edge will not form
the cycle and increment the index for result and add this edge
to result.
self.union(parent, rank, x, y)
print("Following are the edges in the constructed MST") # Print
the statement.
for u, v, weight in result:# Loop upto the result get null
print("%d -
%d = %d" % (u, v, weight))$\# Print the source,Destination,weight
respectively.
g = Graph(5)# Create a graph of 5 vertices
g.addEdge(0, 1, 16)
g.addEdge(0, 2, 3)
g.addEdge(0, 3, 6)
g.addEdge(0, 4,10)
g.addEdge(1, 2, 5)
g.addEdge(2, 3, 9)
g.addEdge(2, 4, 17)
g.addEdge(3, 4, 4) # Add each edges as source ,Destination,weight
respectively.
g.KruskalMST() # Call the main function to proceed.
Output:
Following are the edges in the constructed MST
0 - 2 = 3
3 - 4 = 4
1 - 2 = 5
0 - 3 = 6
Applications:
TV network
Tour Operations
Navigation Systems