Unit 5 DSD Notes
Unit 5 DSD Notes
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
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
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
dead end
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
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
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).
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).
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
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
Add a vertex
Add an edge
Creating a graph
Example:
V = {a, b, c, d, e}
{'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
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
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
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'}]
Representing Graphs
o Adjacency Matrix
o Adjacency List
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
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
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 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 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
bfs_traversal = []
vis = [False]*V
for i in range(V):
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
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 7 - When stack becomes Empty, then produce final spanning tree by
removing unused edges from the graph
Implementation
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
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")])
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")
https://stackoverflow.com/questions/741877/how-do-i-tell-matplotlib-that-i-am-
done-with-a-plot
plt.clf()
Output
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
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
The resulting array at the end of the process is called the topological
ordering of the directed acyclic graph.
Example
Solution-
The topological orderings of the above graph are found in the following
steps-
Step-01:
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:
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
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
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
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);
graph.topologicalSort()
Applications
1. Topological sort can be used to quickly find the shortest paths from the
weighted directed acyclic graph.
6. Topological sort is very useful to find sentence ordering in very fewer efforts
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
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
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
If the path length of the adjacent vertex is lesser than new path length, don't
update it
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
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():
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
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
g.dijkstra(0)
Output
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
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
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
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
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.
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
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 3: Choose the shortest edge from this vertex and add it.
Step 5: Choose the nearest edge not yet in the solution, if there are multiple
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
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