Algorithms
Algorithms
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.
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.
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 .
# 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:
Graph:
Python Code:
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:
Python Code:
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)
Output:
Applications:
TV network
Tour Operations
Navigation Systems