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

Unit-5

A graph is a non-linear data structure consisting of vertices (nodes) and edges (links) connecting them, represented as G = (V, E). It includes various terminologies such as directed and undirected edges, types of graphs, and traversal techniques like Depth First Search (DFS) and Breadth First Search (BFS). The document also discusses algorithms for finding minimum spanning trees, specifically Prim's and Kruskal's algorithms, which are used to determine the least costly paths in a network.

Uploaded by

Sanika Deshmukh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit-5

A graph is a non-linear data structure consisting of vertices (nodes) and edges (links) connecting them, represented as G = (V, E). It includes various terminologies such as directed and undirected edges, types of graphs, and traversal techniques like Depth First Search (DFS) and Breadth First Search (BFS). The document also discusses algorithms for finding minimum spanning trees, specifically Prim's and Kruskal's algorithms, which are used to determine the least costly paths in a network.

Uploaded by

Sanika Deshmukh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

GRAPHS

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

Generally, a graph G is represented as G = ( V , E ), where V is set of vertices and

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 Edge - A directed edge is a unidirectional edge. If there is a directed edge


between vertices A and B then edge (A , B) is not equal to edge (B , A).

Weighted Edge - A weighted edge is an edge with cost on it.


Graph Terminology
Undirected Graph:- A graph with only undirected edges is said to be undirected graph.

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.

Destination:-If an edge is directed, its first endpoint is said to be origin of it


and the other endpoint is said to be the destination of the edge.

Adjacent:-If there is an edge between vertices A and B then both A and B


are said to be adjacent. In other words, Two vertices A and B are said to be
adjacent if there is an edge whose end vertices are A and B.

Incident:-An edge is said to be incident on a vertex if the vertex is one of


the endpoints of that edge.
Outgoing Edge:-A directed edge is said to be outgoing edge on its origin vertex.
Incoming Edge:-A directed edge is said to be incoming edge on its destination vertex.
Degree:-Total number of edges connected to a vertex is said to be degree of that vertex.
In-degree:-Total number of incoming edges connected to a vertex is said to be in-degree of
that vertex.
Out degree:-Total number of outgoing edges connected to a vertex is said to be out degree of
that vertex.
Parallel edges or Multiple edges:-If there are two undirected edges to have the same end vertices,
and for two directed edges to have the same origin and the same destination. Such edges are called
parallel edges or multiple edges.
Self-loop:-An edge (undirected or directed) is a self-loop if its two endpoints coincide.

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...

Directed graph representation...


Adjacency Matrix Representation
Adjacency Matrix Representation
Graph Representations
Incidence Matrix
In this representation, graph can be represented using a matrix of size total number of
vertices by total number of edges.

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.

This matrix is filled with either 0 or 1 or -1.

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...

DFS (Depth First Search)


BFS (Breadth First Search)
Depth First Search
DFS (Depth First Search)
 DFS traversal of a graph, produces a spanning tree as final result.
 Spanning Tree is a graph without any loops.
 We use Stack data structure with maximum size of total number of vertices in the graph
to implement DFS traversal of a graph.
DFS (Depth First Search)
Algorithm
• 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 adjacent vertex of the vertex which is at top of the stack which is
not visited and push it on to the stack.
• Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex on top of the
stack.
• Step 5: When there is no new vertex to be 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
EXAMPLE
• Back tracking is coming back to the vertex from which we came to current vertex.
Breadth First Search
 BFS traversal of a graph, produces a spanning tree as final result.
 Spanning Tree is a graph without any loops.
 We use Queue data structure with maximum size of total number of vertices in the
graph to implement BFS traversal of a graph.
BFS (Breadth First Search)
ALGORITHM

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 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.

Step 5: Repeat step 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.
Shortest Path Algorithm
Spanning tree
 A spanning tree is a sub-graph of an undirected and a connected graph,
which includes all the vertices of the graph having a minimum possible
number of edges. If a vertex is missed, then it is not a spanning tree.

 The edges may or may not have weights assigned to them.

 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

Minimum Spanning Trees


Prim’s Algorithm
Kruskal’s Algorithm
Minimum Spanning Trees
 A spanning tree of a connected, undirected graph G, is a sub-graph of G which is a tree that
connects all the vertices together. A graph G can have many different spanning trees.

 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 the original graph be:


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.

Example of a Spanning Tree

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 used to find airline routers.

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

How Prim'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 one vertex and keep adding edges with the lowest weight until we reach our
goal.

The steps for implementing Prim's algorithm are as follows:

 Initialize the minimum spanning tree with a vertex chosen at random.


 Find all the edges that connect the tree to new vertices, find the minimum and add it to the
tree
 Keep repeating step 2 until we get a minimum spanning tree
PRIM’S ALGORITHM
PRIM’S ALGORITHM
 Step 1: Select a starting vertex
 Step 2: Repeat Steps 3 and 4 until there are fringe vertices
 Step 3:Select an edge e connecting the tree vertex and fringe vertex that has minimum weight
 Step 4:Add the selected edge and the vertex to the minimum spanning tree T
• Step 1 Remove all loops and parallel edges

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.

 The steps for implementing Kruskal's algorithm are as follows:

 Sort all the edges from low weight to high


 Take the edge with the lowest weight and add it to the spanning tree.
 If adding the edge created a cycle, then reject this edge.
 Keep adding edges until we reach all vertices.
Kruskal's Spanning Tree Algorithm
Step 1: Remove all loops and Parallel Edges
 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 :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.

3 Label the initial node with 0, and insert it into N.

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.

The execution of this algorithm will produce either of two results

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

 Floyd Warshall Algorithm is a famous algorithm.


 It is used to solve All Pairs Shortest Path Problem.
 It computes the shortest path between every pair of vertices of the given graph.
 Floyd Warshall Algorithm is an example of dynamic programming approach.

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.

WHEN FLOYD WARSHALL ALGORITHM IS USED?


 Floyd Warshall Algorithm is best suited for dense graphs.
 This is because its complexity depends only on the number of vertices in the given
graph.
 For sparse graphs, Johnson’s Algorithm is more suitable.
PROBLEM BASED ON FLOYD WARSHALL ALGORITHM

Consider the following directed weighted 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:

 Using Floyd Warshall Algorithm, write the following 4 matrices


 In a similar way, A2 is created using A3. The elements in the second column and the second row are
left as they are.

 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

 To find the shortest path is a directed graph


 To find the transitive closure of directed graphs
 To find the Inversion of real matrices
 For testing whether an undirected graph is bipartite
// Floyd-Warshall Algorithm in C
int main()
} {
#include <stdio.h>
} int graph[nV][nV] = {{0, 3, INF, 5},
// defining the number of vertices
} {2, 0, INF, 4},
#define nV 4
printMatrix(A); {INF, 1, 0, INF},
#define INF 999
} {INF, INF, 2, 0}};
void printMatrix(int A[][nV]);
void printMatrix(int A[][nV]) floydWarshall(graph);
void floydWarshall(int graph[][nV])
{ }
{
for (int i = 0; i < nV; i++)
int A[nV][nV], i, j, k;
{
for (i = 0; i < nV; i++)
for (int j = 0; j < nV; j++)
for (j = 0; j < nV; j++)
{
A[i][j] = graph[i][j];
if (A[i][j] == INF)
for (k = 0; k < nV; k++)
printf("%4s", "INF");
{
else
for (i = 0; i < nV; i++)
printf("%4d", A[i][j]);
{
}
for (j = 0; j < nV; j++)
printf("\n");
{
}
if (A[i][k] + A[k][j] < A[i][j])
}
A[i][j] = A[i][k] + A[k][j];
TOPOLOGICAL SORT
TOPOLOGICAL SORT
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.

 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.

 In simple words, a topological ordering of a DAG G, is an ordering of its vertices such


that any directed path in G, traverses vertices in increasing order.
Applications of Topological Sort

Few important applications of topological sort are

 Scheduling jobs from the given dependencies among jobs


 Instruction Scheduling
 Determining the order of compilation tasks to perform in makefiles
 Data Serialization
For this graph, following 4 different topological
orderings are possible

 123456
 123465
 132456
 132465
Topological Sorting
 Algorithm to find a Topological Sort T of a Directed Acyclic Graph, G

 Step 1: Find the indegree INDEG(N) of every node in the graph


 Step 2: Enqueue all the nodes with a zero in-degree
 Step 3: Repeat Steps 4 and 5 until the QUEUE is empty
 Step 4: Remove the front node N of the QUEUE by setting FRONT = FRONT + 1
 Step 5: Repeat for each neighbor M of node N:
a) Delete the edge from N to M by setting INDEG(M) = INDEG(M) – 1
b) IF INDEG(M) = 0, then Enqueue M, that is, add M to the rear of the queue
 [END OF INNER LOOP]
 [END OF LOOP]
 Step 6: Exit
PRACTICE PROBLEMS BASED ON TOPOLOGICAL SORT

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


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.
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:
Now, the above two cases are continued separately in the similar manner.
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.
CONCLUSION
For the given graph, following 2 different topological orderings are possible

 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

You might also like