0% found this document useful (0 votes)
19 views

Unit 5 DSD Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Unit 5 DSD Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

AD3251 – Data structures and Design Unit 5 Mailam Engineering College

MAILAM ENGINEERING COLLEGE, Mailam – 604 304


(Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai

A TATA Consultancy Services Accredited Institution)

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

UNIT V GRAPH STRUCTURES

Graph ADT – representations of graph – graph traversals – DAG – topological


ordering – shortest paths – minimum spanning trees

PART A

1. Define Graph.
A graph data structure is a collection of nodes that have data and are
connected to other nodes.
2. Define adjacent nodes.
 Any two nodes which are connected by an edge in a graph are called
adjacent nodes.
 For example, if an edge x ε E is associated with a pair of nodes (u,v) where u,
v ε V, then we say that the edge x connects the nodes u and v.
3. What is a directed graph?
 A graph in which every edge is directed is called a directed graph.
4. What is an undirected graph?
 A graph in which every edge is undirected is called a directed graph.
5. What is a loop?
 An edge of a graph which connects to itself is called a loop or sling.
6. What is a simple graph?
 A simple graph is a graph, which has not more than one edge between a pair
of nodes than such a graph is called a simple graph.
7. What is a weighted graph?
 A graph in which weights are assigned to every edge is called a weighted
graph.
8. Define outdegree of a graph.
 In a directed graph, for any node v, the number of edges which have v as
their initial node is called the out degree of the node v.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 1
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

9. Define indegree of a graph.


 In a directed graph, for any node v, the number of edges which have v as
their terminal node is called the indegree of the node v.
10. Define path in a graph.
 The path in a graph is the route taken to reach terminal node from a starting
node.
11. What is a simple path?
 A path in a diagram in which the edges are distinct is called a simple path. It
is also called as edge simple.
12. What is a cycle or a circuit?
 A path which originates and ends in the same node is called a cycle or
circuit.
13. What is an acyclic graph?
 A simple diagram which does not have any cycles is called an acyclic graph.
14. What is meant by strongly connected in a graph?
 An undirected graph is connected, if there is a path from every vertex to
every other vertex. A directed graph with this property is called strongly
connected.
15. When is a graph said to be weakly connected?
 When a directed graph is not strongly connected but the underlying graph is
connected, then the graph is said to be weakly connected.
16. Name the different ways of representing a graph?
a) Adjacency matrix
b) Adjacency list
17. What is an undirected acyclic graph?
 When every edge in an acyclic graph is undirected, it is called an undirected
acyclic graph. It is also called as undirected forest.
18. What are the two traversal strategies used in traversing a graph?
a) Breadth first search
b) Depth first search
19. What is a minimum spanning tree?
 A minimum spanning tree of an undirected graph G is a tree formed from
graph edges that connects all the vertices of G at the lowest total cost.
20. Name two algorithms two find minimum spanning tree.
a) Kruskal’s algorithm
b) Prim’s algorithm

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 2
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

21. Define graph traversals.


 Traversing a graph is an efficient way to visit each vertex and edge exactly
once.
22. List the two important key points of depth first search.
a) If path exists from one node to another node, walk across the edge –
exploring the edge.
b) If path does not exist from one specific node to any other node, return to the
previous node where we have been before – backtracking.
23. What do you mean by breadth first search (BFS)?
 BFS performs simultaneous explorations starting from a common point and
spreading out independently.
24. What do you mean by tree edge?
 If w is undiscovered at the time vw is explored, then vw is called a tree edge
and v becomes the parent of w.
25. What do you mean by back edge?
 If w is the ancestor of v, then vw is called a back edge.
26. Define biconnectivity.
 A connected graph G is said to be biconnected, if it remains connected after
removal of any one vertex and the edges that are incident upon that vertex.
 A connected graph is biconnected, if it has no articulation points.
27. What do you mean by articulation point?
 If a graph is not biconnected, the vertices whose removal would disconnect
the graph are known as articulation points.
28. What do you mean by shortest path?
 A path having minimum weight between two vertices is known as shortest
path, in which weight is always a positive number.
29. Define Activity node graph.
 Activity node graphs represent a set of activities and scheduling constraints.
Each node represents an activity (task), and an edge represents the next
activity.
30. Define adjacency list.
 Adjacency list is an array indexed by vertex number containing linked lists.
Each node Vi the ith array entry contains a list with information on all edges
of G that leave Vi.
 It is used to represent the graph related problems.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 3
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

31. Differentiate BFS and DFS.

S. No. DFS BFS

1. Backtracking is possible from a Backtracking is not possible

dead end

2. Vertices from which exploration The vertices to be explored are


is incomplete are processed in a organized as a FIFO queue
LIFO order

3. Search is done in one particular The vertices in the same level are
maintained
direction

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 4
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

PART B

1. Explain in detail about the Introduction of Graph ADT.


 Graph
 Graph Terminology
 Types of Graphs
 Applications of Graphs

Graph

 A graph data structure is a collection of nodes that have data and are
connected to other nodes.
 A graph is an ordered pair G = (V, E) comprising a set V of vertices or

nodes and a collection of pairs of vertices from V , known as edges of a

graph as shown in figure 5.1.

Figure 5.1 Representation of graph

Graph Terminology
 Vertex − Each node of the graph is represented as a vertex.
 Edge − Edge represents a path between two vertices or a line between two
vertices.
 Adjacency − Two node or vertices are adjacent if they are connected to each
other through an edge.
 Path − Path represents a sequence of edges between the two vertices.
 Degree of a Node: Degree of a node is the number of edges connecting the
node in the graph.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 5
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Types of Graphs

1. Undirected Graphs
 In an undirected graph, the edges have no path or direction. If there is a
path from vertex X to vertex Y, then there is a path from vertex Y to vertex X.
Edge (X, Y) represents the edge connecting vertex X to vertex Y.
 That is, edge (X, Y) == edge (Y, X).

2. Directed Graphs
 In a directed graph or digraph, the edges have an orientation. If there is a
path from vertex X to vertex Y, then there isn’t necessarily a path from vertex
Y to vertex X.
 That is, edge (X, Y) != edge (Y, X).

3. Weighted Graphs
 A weighted graph has a value associated with every edge. The value may
represent quantities like cost, distance, time, etc., depending on the graph.
An edge of a weighted graph is represented as, (u, v, w).

o u -> Source vertex

o v -> Destination vertex

o w -> Weight associated to go from u to v.

 These weighted graphs are extensively used in modelling Computer


Networks.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 6
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

4. Unweighted Graphs
 An unweighted graph does not have a value associated with every edge. An
edge of an unweighted graph is represented as, (u, v).

o u -> Source vertex

o v -> Destination vertex

 Relationships in query languages like Graph QL can be represented by using


Unweighted Graphs.

5. Directed Acyclic Graphs


 Directed Acyclic Graphs or DAGs are graphs with no directed cycles. They
represent structures with dependencies.
 Directed Acyclic Graphs are used by compilers to represent expressions and
relationships in a program.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 7
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

6. Complete Graphs
 Complete graphs have a unique edge between every pair of vertices. A
complete graph n vertices have (n*(n-1)) / 2 edges and are represented by
Kn.
 Fully connected networks in a Computer Network uses a complete graph in
its representation.

Applications of Graphs

 To visualize organized data.

 Directed Graphs are used in Google’s Page Ranking Algorithm.

 Social Networks use graphs to represent different users as vertices and


edges to represent the connections between them.

 In a mapping application, graphs are used to represent places and the path
(distance) between them.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 8
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

2. Explain in detail about the implementations of Graph ADT.

Basic operations on graphs

 Display graph vertices

 Display graph edges

 Add a vertex

 Add an edge

 Creating a graph

Example:

In the above graph,

V = {a, b, c, d, e}

E = {ab, ac, bd, cd, de}

# Create the dictionary with graph elements


graph = {
"a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
# Print the graph
print(graph)
Output

{'c': ['a', 'd'], 'a': ['b', 'c'], 'e': ['d'], 'd': ['e'], 'b': ['a', 'd']}

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 9
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Display graph vertices

class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = []
self.gdict = gdict
# Get the keys of the dictionary
def getVertices(self):
return list(self.gdict.keys())
# Create the dictionary with graph elements
graph_elements = {
"a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
g = graph(graph_elements)
print(g.getVertices())
Output

['d', 'b', 'e', 'c', 'a']

Display graph edges

class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict

def edges(self):
return self.findedges()
# Find the distinct list of edges
def findedges(self):
edgename = []
for vrtx in self.gdict:
for nxtvrtx in self.gdict[vrtx]:
if {nxtvrtx, vrtx} not in edgename:
edgename.append({vrtx, nxtvrtx})
return edgename
graph_elements = {
"a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
g = graph(graph_elements)

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 10
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

print(g.edges())
Output

[{'b', 'a'}, {'b', 'd'}, {'e', 'd'}, {'a', 'c'}, {'c', 'd'}]
Adding a vertex

class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def getVertices(self):
return list(self.gdict.keys())
# Add the vertex as a key
def addVertex(self, vrtx):
if vrtx not in self.gdict:
self.gdict[vrtx] = []
# Create the dictionary with graph elements
graph_elements = {
"a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
g = graph(graph_elements)
g.addVertex("f")
print(g.getVertices())
Output

['f', 'e', 'b', 'a', 'c','d']

Adding an edge

class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def edges(self):
return self.findedges()
# Add the new edge
def AddEdge(self, edge):
edge = set(edge)
(vrtx1, vrtx2) = tuple(edge)
if vrtx1 in self.gdict:
self.gdict[vrtx1].append(vrtx2)
else:

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 11
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

self.gdict[vrtx1] = [vrtx2]
# List the edge names
def findedges(self):
edgename = []
for vrtx in self.gdict:
for nxtvrtx in self.gdict[vrtx]:
if {nxtvrtx, vrtx} not in edgename:
edgename.append({vrtx, nxtvrtx})
return edgename
# Create the dictionary with graph elements
graph_elements = {
"a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
g = graph(graph_elements)
g.AddEdge({'a','e'})
g.AddEdge({'a','c'})
print(g.edges())
Output

[{'e', 'd'}, {'b', 'a'}, {'b', 'd'}, {'a', 'c'}, {'a', 'e'}, {'c', 'd'}]

3. Explain in detail about the representations of Graphs.

Representing Graphs

 There are multiple ways of using data structures to represent a graph.


The three most common ways are:

o Adjacency Matrix

o Adjacency List

 An adjacency matrix can be thought of as a table with rows and


columns. The row labels and column labels represent the nodes of a
graph.
 An adjacency matrix is a square matrix where the number of rows,
columns and nodes are the same.
 Each cell of the matrix represents an edge or the relationship between
two given nodes.
 For example, adjacency matrix Aij represents the number of links from i
to j, given two nodes i and j.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 12
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Fig. Adjacency Matrix for Undirected Graph

Fig. Adjacency Matrix for Directed Graph

Fig. Adjacency Matrix for Weighted Graph

 In adjacency list representation of a graph, every vertex is represented as a


node object. The node may either contain data or a reference to a linked list.
 This linked list provides a list of all nodes that are adjacent to the current
node.
 Consider a graph containing an edge connecting node A and node B. Then,
the node A will be available in node B’s linked list.
 Fig shows a sample graph of 5 nodes and its corresponding adjacency list.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 13
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Fig. Adjacency List for a Directed Graph

Fig. Adjacency List for Undirected Graph

 Adjacency list enables faster search process in comparison to adjacency


matrix. It is not the best representation of graphs especially when it comes
to adding or removing nodes.
 For example, deleting a node would involve looking through all the
adjacency lists to remove a particular node from all lists.

3. Explain in detail about Graph Traversals methods.

 Graph traversal is a technique used for searching a vertex in a graph. The


graph traversal is also used to decide the order of vertices is visited in the
search process.
 A graph traversal finds the edges to be used in the search process without
creating loops. That means using graph traversal we visit all the vertices of
the graph without getting into looping path.
 There are two graph traversal techniques and they are as follows

1. DFS (Depth First Search)

2. BFS (Breadth First Search)

BFS (Breadth First Search)

The following steps are used to implement BFS traversal

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 14
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Step 1 - Define a Queue of size total number of vertices in the graph.

Step 2 - Select any vertex as starting point for traversal. Visit that vertex and
insert it into the Queue.

Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front
of the Queue and insert them into the Queue.

Step 4 - When there is no new vertex to be visited from the vertex which is at
front of the Queue then delete that vertex.

Step 5 - Repeat steps 3 and 4 until queue becomes empty.

Step 6 - When queue becomes empty, then produce final spanning tree by
removing unused edges from the graph

Example

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 15
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 16
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Implementation

def bfsOfGraph(V, adj):

bfs_traversal = []
vis = [False]*V
for i in range(V):

# To check if already visited


if (vis[i] == False):
q = []
vis[i] = True
q.append(i)

# BFS starting from ith node


while (len(q) > 0):
g_node = q.pop(0)

bfs_traversal.append(g_node)
for it in adj[g_node]:
if (vis[it] == False):
vis[it] = True
q.append(it)

return bfs_traversal

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 17
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

DFS (Depth First Search)

Steps to implement DFS traversal

Step 1 - Define a Stack of size total number of vertices in the graph.

Step 2 - Select any vertex as starting point for traversal. Visit that vertex and
push it on to the Stack.

Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at
the top of stack and push it on to the stack.

Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex
which is at the top of the stack.

Step 5 - When there is no new vertex to visit then use back tracking and pop
one vertex from the stack.

Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.

Step 7 - When stack becomes Empty, then produce final spanning tree by
removing unused edges from the graph

Implementation

from collections import defaultdict


class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited.add(v)
print(v, end=' ')
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set()
self.DFSUtil(v, visited)
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.DFS(2)

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 18
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Example

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 19
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 20
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 21
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 22
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

5. Explain in detail about DAG (Directed Acyclic Graph).

 A directed acyclic graph (DAG) is a graph that is directed and without cycles
connecting the other edges.
 This means that it is impossible to traverse the entire graph starting at one
edge.
 The edges of the directed graph only go one way.
 A directed acyclic graph means that the graph is not cyclic, or that it is
impossible to start at one point in the graph and traverse the entire graph.
 Each edge is directed from an earlier edge to a later edge. This is also known
as a topological ordering of a graph.

Example 1

Fig. DAG
 root, a, b, c, d, and e are referred to as nodes. The arrows that connect the
nodes are called edges. A graph is a collection of nodes that are connected by
edges. A directed acyclic graph is a special type of graph with properties

Implementation

import networkx as nx

graph = nx.DiGraph()

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 23
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

graph.add_edges_from([("root", "a"), ("a", "b"), ("a", "e"), ("b", "c"), ("b", "d"),
("d", "e")])

graph.nodes() # => NodeView(('root', 'a', 'b', 'e', 'c', 'd'))

from matplotlib import pyplot as plt

g1 = nx.DiGraph()

g1.add_edges_from([("root", "a"), ("a", "b"), ("a", "e"), ("b", "c"), ("b", "d"), ("d", "e")])

plt.tight_layout()

nx.draw_networkx(g1, arrows=True)

plt.savefig("g1.png", format="PNG")

# tell matplotlib you're done with the plot:

https://stackoverflow.com/questions/741877/how-do-i-tell-matplotlib-that-i-am-
done-with-a-plot

plt.clf()

Output

6. Explain in detail about Topological Ordering.

 Topological Sort is a linear ordering of the vertices in such a way that

if there is an edge in the DAG going from vertex ‘u’ to vertex ‘v’, then ‘u’
comes before ‘v’ in the ordering.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 24
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

 Topological Sorting is possible if and only if the graph is a Directed


Acyclic Graph.
 There may exist multiple different topological orderings for a given
directed acyclic graph.

Algorithm

1. Identify the node that has no in-degree(no incoming edges) and select that
node as the source node of the graph

2. Delete the source node with zero in-degree and also delete all its outgoing
edges from the graph. Insert the deleted vertex in the result array.

3. Update the in-degree of the adjacent nodes after deleting the outgoing edges

4. Repeat step 1 to step 3 until the graph is empty

The resulting array at the end of the process is called the topological
ordering of the directed acyclic graph.

Example

Find the number of different topological orderings possible for the


given graph-

Solution-

The topological orderings of the above graph are found in the following
steps-

Step-01:

 Write in-degree of each vertex-

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 25
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Step-02:
 Vertex-A has the least in-degree.
 So, remove vertex-A and its associated edges.
 Now, update the in-degree of other vertices.

Step-03:

 Vertex-B has the least in-degree.


 So, remove vertex-B and its associated edges.
 Now, update the in-degree of other vertices.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 26
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Step-04:
 There are two vertices with the least in-degree.
 So, following 2 cases are possible-
In case-01,
 Remove vertex-C and its associated edges.
 Then, update the in-degree of other vertices.
In case-02,
 Remove vertex-D and its associated edges.
 Then, update the in-degree of other vertices.

Step-05:

In case-01,
 Remove vertex-D since it has the least in-degree.
 Then, remove the remaining vertex-E.
In case-02,
 Remove vertex-C since it has the least in-degree.
 Then, remove the remaining vertex-E.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 27
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

For the given graph, following 2 different topological orderings are possible-
 ABCDE
 ABDCE

 If due to some reason, there are some nodes left but they have the incoming
edges, that means that the graph is not an acyclic graph and topological
ordering does not exist.

Implementation

from collections import defaultdict

class Graph:

def __init__(self,n):

self.graph = defaultdict(list)

self.N = n

def addEdge(self,m,n):

self.graph[m].append(n)

def sortUtil(self,n,visited,stack):

visited[n] = True

for element in self.graph[n]:

if visited[element] == False:

self.sortUtil(element,visited,stack)

stack.insert(0,n)

def topologicalSort(self):

visited = [False]*self.N

stack =[]

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 28
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

for element in range(self.N):

if visited[element] == False:

self.sortUtil(element,visited,stack)

print(stack)

graph = Graph(5)
graph.addEdge(0,1);
graph.addEdge(0,3);
graph.addEdge(1,2);
graph.addEdge(2,3);
graph.addEdge(2,4);
graph.addEdge(3,4);

print("The Topological Sort Of The Graph Is: ")

graph.topologicalSort()

Applications

1. Topological sort can be used to quickly find the shortest paths from the
weighted directed acyclic graph.

2. It is used to check whether there exists a cycle in the graph or not

3. Topological sort is useful to find the deadlock condition in an operating


system

4. It is used in course scheduling problems to schedule jobs

5. It is used to find the dependency resolution

6. Topological sort is very useful to find sentence ordering in very fewer efforts

7. It is used in manufacturing workflows or data serialization in an application

8. It is used for ordering the cell evaluation while recomputing formula values
in an excel sheet or spreadsheet.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 29
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

7. Explain in detail about Shortest path algorithm or Dijkstra's Algorithm.


 Dijkstra's Algorithm
 Working of Dijkstra's Algorithm
 Implementation
 Applications

Dijkstra's Algorithm:
 Dijkstra's algorithm is used to find the shortest path between any two
vertices of a graph.
 The algorithm is purely based on greedy approach and thus finds the
locally optimal choice at each step of the algorithm.
Greedy algorithm:
 A greedy algorithm is an approach for solving a problem by selecting the
best option available at the moment. It doesn't worry whether the
current best result will bring the overall optimal result.
Working of Dijkstra's Algorithm:
1. Mark the source node with a current distance of 0 and the rest with
infinity.
2. Set the non-visited node with the smallest current distance as the
current node, lets say C.
3. For each neighbor N of the current node C: add the current distance
of C with the weight of the edge connecting C to N. If it is smaller than
the current distance of N, set it as the new current distance of N.
4. Mark the current node C as visited.
5. Go to step 2 if there are any nodes are unvisited.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 30
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Example of Dijkstra's algorithm

Start with a weighted graph

Choose a starting vertex and assign infinity path values to all other devices

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 31
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Go to each vertex and update its path length

If the path length of the adjacent vertex is lesser than new path length, don't
update it

Avoid updating path lengths of already visited vertices

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 32
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

After each iteration, pick the unvisited vertex with the least path length. So choose
5 before 7

Notice how the rightmost vertex has its path length updated twice

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 33
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Repeat until all the vertices have been visited

Solution
Vertex Distance from Source
0 -> 0 0
0 -> 1 4
0 -> 2 4
0 -> 3 7 (0 -> 2 -> 3)
0 -> 4 5 (0 -> 2 -> 4)
0 -> 5 8 (0 -> 2 -> 4 -> 5)

Implementation:
import sys

class Graph():

def __init__(self, vertices):


self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]

def printSolution(self, dist):


print("Vertex \tDistance from Source")

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 34
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

for node in range(self.V):


print(node, "\t", dist[node])

def minDistance(self, dist, sptSet):

min = sys.maxsize

for u in range(self.V):
if dist[u] < min and sptSet[u] == False:
min = dist[u]
min_index = u
return min_index
def dijkstra(self, src):
dist = [sys.maxsize] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):

x = self.minDistance(dist, sptSet)
sptSet[x] = True
for y in range(self.V):
if self.graph[x][y] > 0 and sptSet[y] == False and \
dist[y] > dist[x] + self.graph[x][y]:
dist[y] = dist[x] + self.graph[x][y]

self.printSolution(dist)

# Driver's code
if __name__ == "__main__":
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 35
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

[0, 0, 0, 9, 0, 10, 0, 0, 0],


[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]

g.dijkstra(0)

Output

Vertex Distance from Source


0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

Time Complexity: O(V2)


Auxiliary Space: O(V)

Dijkstra's Algorithm Applications


 To find the shortest path
 In social networking applications
 In a telephone network
 To find the locations in the map

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 36
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Dijkstra's Algorithm Example

Solution - Vertex Distance from Source V1


V1 0
V2 2
V3 3
V4 1
V5 3
V6 6
V7 5

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 37
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

9. Explain in detail about minimum spanning tree.


 Spanning tree
 Minimum Spanning Tree
 General Properties of Spanning Tree
 Mathematical Properties of Spanning Tree
 Application of Spanning Tree
 Minimum Spanning-Tree Algorithm
 Kruskal's Algorithm
 Prim's Algorithm
Spanning tree
 A spanning tree is a sub-graph of an undirected connected graph, which
includes all the vertices of the graph with a minimum possible number of
edges.
Minimum Spanning Tree
 A minimum spanning tree is a spanning tree in which the sum of the weight
of the edges is as minimum as possible.

General Properties of Spanning Tree


 A connected graph G can have more than one spanning tree.
 All possible spanning trees of graph G, have the same number of edges and
vertices.
 The spanning tree does not have any cycle (loops).
 Removing one edge from the spanning tree will make the graph disconnected,
i.e. the spanning tree is minimally connected.
 Adding one edge to the spanning tree will create a circuit or loop, i.e. the
spanning tree is maximally acyclic.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 38
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Application of Spanning Tree


 Civil Network Planning
 Computer Network Routing Protocol
 Cluster Analysis

10. Explain in detail about Kruskal's Spanning Tree Algorithm.


 Kruskal's Spanning Tree Algorithm
 Creating Minimum Spanning Tree Using Kruskal Algorithm

Kruskal's Spanning Tree Algorithm:


 Kruskal's algorithm to find the minimum cost spanning tree uses the greedy
approach.
Creating Minimum Spanning Tree Using Kruskal Algorithm
Step 1: Sort all edges in increasing order of their edge weights.
Step 2: Pick the smallest edge.
Step 3: Check if the new edge creates a cycle or loop in a spanning tree.
Step 4: If it doesn’t form the cycle, then include that edge in MST. Otherwise,
discard it.
Step 5: Repeat from step 2 until it includes |V| - 1 edges in MST.

The graph G(V, E) given below contains 6 vertices and 12 edges. And create a
minimum spanning tree T(V’, E’) for G(V, E) such that the number of vertices in
T will be 6 and edges will be 5 (6-1).

 The next step is arranging all edges in a sorted list by their edge weights.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 39
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

The Edges of the Graph Edge Weight

Source Vertex Destination Vertex


E F 2
F D 2
B C 3
C F 3
C D 4
B F 5
B D 6
A B 7
A C 8

 Include edges in the MST such that the included edge would not form a cycle
in your tree structure. The first edge that you will pick is edge EF, as it has a
minimum edge weight that is 2.
 Include edges in the MST such that the included edge would not form a cycle
in your tree structure. The first edge that you will pick is edge EF, as it has a
minimum edge weight that is 2.

 Add edge FD to the spanning tree.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 40
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

 Add edge BC and edge CF to the spanning tree as it does not generate any
loop.

 Next up is edge CD. This edge generates the loop in the tree structure. Thus,
discard this edge.

 Following edge CD, you have edge BF. This edge also creates the loop; hence
you will discard it.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 41
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

 Next up is edge BD. This edge also formulates a loop, so you will discard it
as well.

 Next on sorted list is edge AB. This edge does not generate any cycle, so need
not include it in the MST structure. By including this node, it will include 5
edges in the MST, so don’t have to traverse any further in the sorted list. The
final structure of your MST is represented in the image below:

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 42
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

 The summation of all the edge weights in MST T(V’, E’) is equal to 17, which
is the least possible edge weight for any possible spanning tree structure for
this particular graph.
Kruskal's Algorithm Applications
 Network Design
 Approximation Algorithms
 Image Segmentation
 Clustering

11. Explain in detail about Prim’s Algorithm.


Prim's Algorithm
 Prim's algorithm is a minimum spanning tree algorithm that takes a
graph as input and finds the subset of the edges of that graph which
 form a tree that includes every vertex
 has the minimum sum of weights among all the trees that can be
formed from the graph
Working of Prim's algorithm
 It falls under a class of algorithms called greedy algorithms that find the
local optimum in the hopes of finding a global optimum.
 Start from one vertex and keep adding edges with the lowest weight until
the goal is reached.
The steps for implementing Prim's algorithm are as follows:
1. Initialize the minimum spanning tree with a vertex chosen at random.
2. Find all the edges that connect the tree to new vertices, find the
minimum and add it to the tree.
3. Keep repeating step 2 until we get a minimum spanning tree.
Step 1: Start with a weighted graph.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 43
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Step 2: Choose a vertex.

Step 3: Choose the shortest edge from this vertex and add it.

Step 4: Choose the nearest vertex not yet in the solution

Step 5: Choose the nearest edge not yet in the solution, if there are multiple

choices, choose one at random.

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 44
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Step 6: Repeat until you have a spanning tree.

Prim's Algorithm pseudo code


T = ∅;
U = { 1 };
while (U ≠ V)
let (u, v) be the lowest cost edge such that u ∈ U and v ∈ V - U;
T = T ∪ {(u, v)}
U = U ∪ {v}

Prim's Algorithm Application


 Laying cables of electrical wiring
 In network designed
 To make protocols in network cycles

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 45
AD3251 – Data structures and Design Unit 5 Mailam Engineering College

Prepared By: Dr. S. Artheeswari Prof. / AI&DS and Ms.M.Nithya, AP/AI&DS Page 46

You might also like