Unit-5
Unit-5
DEFINITION
Graph is a non linear data structure, it contains a set of points known as nodes (or
vertices) and set of links known as edges (or Arcs) which connects the vertices. A graph is
defined as follows...
Graph is a collection of vertices and arcs which connects vertices in the graph
Graph is a collection of nodes and edges which connects nodes in the graph
E is set of edges.
GRAPHS
Example
The following is a graph with 5 vertices and 7 edges.
This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and
E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.
Graph Terminology
Vertex
A individual data element of a graph is called as Vertex. Vertex is also known
as node. In above example graph, A, B, C, D & E are known as vertices.
Edge
An edge is a connecting link between two vertices.
Edge is also known as Arc.
An edge is represented as (starting Vertex, ending Vertex).
For example, in above graph, the link between vertices A and B is represented as
(A,B). In above example graph, there are 7 edges (i.e., (A,B), (A,C), (A,D), (B,D),
(B,E), (C,D), (D,E)).
Edges are three types.
Undirected Edge - An undirected edge is a bidirectional edge. If there is a undirected
edge between vertices A and B then edge (A , B) is equal to edge (B , A).
Directed Graph:-A graph with only directed edges is said to be directed graph.
Mixed Graph:-A graph with undirected and directed edges is said to be mixed graph.
End vertices or Endpoints:-The two vertices joined by an edge are called the end
vertices (or endpoints) of the edge.
Origin:-If an edge is directed, its first endpoint is said to be origin of it.
Simple Graph:-A graph is said to be simple if there are no parallel and self-loop
edges.
Path:-A path is a sequence of alternating vertices and edges that starts at a vertex and
ends at a vertex such that each edge is incident to its predecessor and successor vertex.
Graph
Representations
Graph data structure is represented using following representations...
Adjacency Matrix
Incidence Matrix
Adjacency List
a. Adjacency Matrix:-
In this representation, graph can be represented using a matrix of size total number of vertices by total
number of vertices.
That means if a graph with 4 vertices can be represented using a matrix of 4X4 class.
In this matrix, rows and columns both represents vertices.
This matrix is filled with either 1 or 0.
Here, 1 represents there is an edge from row vertex to column vertex and 0 represents there is no edge from
row vertex to column vertex.
• For example, consider the following
undirected graph representation...
That means if a graph with 4 vertices and 6 edges can be represented using a matrix of
4X6 class. In this matrix, rows represents vertices and columns represents edges.
Here, 0 represents row edge is not connected to column vertex, 1 represents row edge
is connected as outgoing edge to column vertex and -1 represents row edge is
connected as incoming edge to column vertex.
• For example, consider the following directed graph representation...
Graph Representations
Adjacency List
• In this representation, every vertex of graph contains list of its adjacent vertices.
For example, consider the following directed graph representation implemented using
linked list...
Graph Array Representations
• This representation can also be implemented using array as follows..
Operations of Graphs
INSERTING
DELETING
MERGING
TRAVERSING
• Graph traversal is technique used for searching a vertex in a graph. The graph traversal is also used to decide
the order of vertices to be visit 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 vertices of graph without getting into looping path.
There are two graph traversal techniques and they are as follows...
Step 2: Select any vertex as starting point for traversal. Visit that vertex and insert it into the
Queue.
Step 3: Visit all the adjacent vertices of the vertex which is at front of the Queue which is not
visited and insert them into the Queue.
Step 4: When there is no new vertex to be visit from the vertex at front of the Queue then delete that
vertex from the Queue.
The total number of spanning trees with n vertices that can be created from
a complete graph is equal to n(n-2).
Shortest Path Algorithm
In this section we will discuss the three different algorithms to calculate the
shortest path in between the vertices of the graph
When we assign weights to each edge (which is a number that represents how unfavorable the edge is),
and use it to assign a weight to a spanning tree by calculating the sum of the weights of the edges in that
spanning tree.
A minimum spanning tree (MST) is defined as a spanning tree with weight less than or equal to the weight
of every other spanning tree. In other words, a minimum spanning tree is a spanning tree that has weights
associated with its edges, and the total weight of the tree (the sum of the weights of its edges) is at a
minimum.
Example of a Spanning Tree
Let's understand the spanning tree with examples below:
Let's understand the above definition with the help of the example below.
The initial graph is:
The possible spanning trees are:
Applications of MST
MST widely used for designing networks.
MST is used to determine the least costly path with no cycles in this network.
MST are also used to find the cheapest way to connect terminals.
MST are applied in routing algorithms for finding the most efficient path.
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
We start from one vertex and keep adding edges with the lowest weight until we reach our
goal.
Remove all loops and parallel edges from the given graph. In case of parallel edges, keep
the one which has the least cost associated and remove all others.
• Step 2 Choose any arbitrary node as root node
• In this case, we choose S node as the root node of Prim's spanning tree. This node is arbitrarily chosen, so any
node can be the root node. One may wonder why any video can be a root node. So the answer is, in the
spanning tree all the nodes of a graph are included and because it is connected then there must be at least
one edge, which will join it to the rest of the tree.
• Step 3 Check outgoing edges and select the one with less cost
• After choosing the root node S, we see that S,A and S,C are two edges with weight 7 and 8, respectively. We
choose the edge S,A as it is lesser than the other.
• Now, the tree S-7-A is treated as one node and we check for all edges going out from it. We select the
one which has the lowest cost and include it in the tree.
• After this step, S-7-A-3-C tree is formed. Now we'll again treat it as a node and will check all the edges
again. However, we will choose only the least cost edge. In this case, C-3-D is the new edge, which is
less than other edges' cost 8, 6, 4, etc.
After adding node D to the spanning tree, we now have two edges going out of it having the same cost, i.e. D-2-T and D-2-B.
Thus, we can add either one. But the next step will again yield edge 2 as the least cost. Hence, we are showing a spanning
tree with both edges included.
Kruskal's ALGORITHM
Kruskal'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.
How Kruskal's algorithm works
It falls under a class of algorithms called greedy algorithms which find the local
optimum in the hopes of finding a global optimum.
We start from the edges with the lowest weight and keep adding edges until we we
reach our goal.
In case of parallel edges, keep the one which has the least cost associated and remove all
others.
• Step 2 :Arrange all edges in their increasing order of weight
• The next step is to create a set of edges and weight, and arrange them in an ascending order of weight
age (cost).
Step 3 : Add the edge which has the least weight age
Now we start adding edges to the graph beginning from the one which has the least weight. Throughout, we
shall keep checking that the spanning properties remain intact. In case, by adding one edge, the spanning tree
property does not hold then we shall consider not to include the edge in the graph.
• The least cost is 2 and edges involved are B,D and D,T. We add them. Adding them does not violate spanning
tree properties, so we continue to our next edge selection.
• Next cost is 3, and associated edges are A,C and C,D. We add them again
Next cost in the table is 4, and we observe that adding it will create a circuit in the graph.
• We ignore it. In the process we shall ignore/avoid all edges that create a circuit.
We observe that edges with cost 5 and 6 also create circuits. We ignore them and move on.
• Now we are left with only one node to be added. Between the two least cost edges available
7 and 8, we shall add the edge with cost 7.
By adding edge S,A we have included all the nodes of the graph and we now have
minimum cost spanning tree.
Transitive Closure
Dijsktra’s Algorithm
Dijkstra's algorithm, given by a Dutch scientist Edsger Dijkstra in 1959, is used to find the
shortest path tree.
This algorithm is widely used in network routing protocols, most notably IS-IS and OSPF
(Open Shortest Path First).
Given a graph G and a source node A, the algorithm is used to find the shortest path
(one having the lowest cost) between A (source node) and every other node.
Moreover, Dijkstra’s algorithm is also used for finding costs of shortest paths from a
source node to a destination node.
Dijsktra’s Algorithm
1 Select the source node also called the initial node
2 Define an empty set N that will be used to hold nodes to which a shortest path has been found.
4 Repeat Steps 5 to 7 until the destination node is in N or there are no more labeled nodes in N.
5 Consider each node that is not in N and is connected by an edge from the newly inserted node.
6 a. If the node that is not in N has no labeled then SET the label of the node = the label of the newly
inserted node + the length of the edge.
• b. Else if the node that is not in N was already labeled, then SET its new label = minimum (label of
newly inserted vertex + length of edge, old label)
7 Pick a node not in N that has the smallest label assigned to it and add it to N
Dijsktra’s Algorithm
Dijkstra's algorithm labels every node in the graph where the labels represent the distance (cost)
from the source node to that node. There are two kinds of labels: temporary and permanent.
While temporary labels are assigned to nodes that have not been reached, permanent labels are
given to nodes that have been reached and their distance (cost) to the source node is known. A
node must be a permanent label or a temporary label, but not both.
If the destination node is labeled, then the label will in turn represent the distance from the source
node to the destination node.
If it the destination node is not labeled, then it means that there is no path from the source to the
destination node.
Dijsktra’s Example
• Example: Consider the graph G given below. Taking the initial node, execute the
Dijkastra’s algorithm on it.
Adjacent vertices of 0 ,1 and 7. The distance values of 1 and 7 are updated as 4 and 8.
Following sub graph shows vertices and their distance values, only the vertices with finite distance values are
shown. The vertices included in SPT are shown in green colour.
The vertex 1 is picked and added to SPT Set. So SPT Set now becomes {0, 1}. Update the distance values of adjacent
vertices of 1. The distance value of vertex 2
Pick the vertex with minimum distance value and not already included in SPT (not in SPT SET). Vertex 7 is
picked. So SPT Set now becomes {0, 1, 7}. Update the distance values of adjacent vertices of 7. The distance
value of vertex 6 and 8 becomes finite (15 and 9 respectively).
Pick the vertex with minimum distance value and not already included in SPT (not in SPT SET). Vertex 6 is
picked. So SPT Set now becomes {0, 1, 7, 6}. Update the distance values of adjacent vertices of 6. The distance
value of vertex 5 and 8 are updated.
We repeat the above steps until SPT SET does include all vertices of given graph. Finally, we get the following
Shortest Path Tree (SPT).
War shall Algorithm
WARSHALL ALGORITHM
ADVANTAGES
It is extremely simple.
It is easy to implement.
TIME COMPLEXITY
Floyd Warshall Algorithm consists of three loops over all the nodes.
The inner most loop consists of only constant complexity operations.
Hence, the asymptotic complexity of Floyd Warshall algorithm is O(n3).
Here, n is the number of nodes in the given graph.
Using Floyd Warshall Algorithm, find the shortest path distance between every
pair of vertices.
STEP-01:
Remove all the self loops and parallel edges (keeping the lowest weight edge) from the
graph.
In the given graph, there are neither self edges nor parallel edges.
STEP-02:
Write the initial distance matrix.
It represents the distance between every pair of vertices in the form of given weights.
For diagonal elements (representing self-loops), distance value = 0.
For vertices having a direct edge between them, distance value = weight of that edge.
For vertices having no direct edge between them, distance value = ∞.
Initial distance matrix for the given graph is
STEP-03:
In this step, k is the second vertex (i.e. vertex 2). The remaining steps are the same as in step 3.
FROM THE A1
SIMILARLY, A3 AND A4 IS ALSO CREATED.
FROM THE A2
Floyd Warshall Algorithm Applications
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.
123456
123465
132456
132465
Topological Sorting
Algorithm to find a Topological Sort T of a Directed Acyclic Graph, G
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:
ABCDE
ABDCE
Topological sorting is widely used in scheduling applications, jobs or tasks. The jobs
that have to be completed are represented by nodes, and there is an edge from node u to
v if job u must be completed before job v can be started. A topological sort of such a
graph gives an order in which the given jobs must be performed.
EXAMPLE - 2
123456
123465
132456
132465