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.
[Link](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 [Link] 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 [Link]
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
[Link](node)
[Link](node)# this checking and appending the starting node to
the list of visited and also in queue.
while queue:
s = [Link](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:
[Link](neighbour)
[Link](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
[Link] = [] # take the graph dictionary as initial
def addEdge(self, u, v, w):# Function to add edges to graph
[Link]([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 [Link](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 = [Link](parent, x)
yroot = [Link](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.
[Link] = sorted([Link], 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
[Link](node)# Creating the set of V with adding
single elements.
[Link](0)
while e < self.V-1:
# Check for condition up to number of vertices equal to vertices-1.
u, v, w = [Link][i]
i += 1 # Take the smallest edge and increment index by one.
x = [Link](parent, u)
y = [Link](parent, v)
if x != y:
e += 1
[Link]([u, v, w]) # Find the edge will not form
the cycle and increment the index for result and add this edge
to result.
[Link](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
[Link](0, 1, 16)
[Link](0, 2, 3)
[Link](0, 3, 6)
[Link](0, 4,10)
[Link](1, 2, 5)
[Link](2, 3, 9)
[Link](2, 4, 17)
[Link](3, 4, 4) # Add each edges as source ,Destination,weight
respectively.
[Link]() # 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