DSA Chap 10 Graph
DSA Chap 10 Graph
DSA Chap 10 Graph
Graph
Graph
A graph is a pictorial representation of a set of objects where some pairs of
objects are connected by links.
Graph is a non linear data structure
A graph is a data structure that consists of the following two components:
A finite set of vertices also called as nodes.
A finite set of ordered pair of the form (u, v) called as edge. The pair is
ordered because (u, v) is not the same as (v, u) in case of a directed graph(di-
graph). The pair of the form (u, v) indicates that there is an edge from vertex
u to vertex v.
The edges may contain \weight/value/cost
In this graph, V = {a, b, c, d, e} E = {ab, ac, bd, cd, de}
Graph as ADT
The graph abstract data type (ADT) is defined as follows:
Graph() creates a new, empty graph.
addVertex(vert) adds an instance of Vertex to the graph.
addEdge(fromVert, toVert) Adds a new, directed edge to the
graph that connects two vertices.
addEdge(fromVert, toVert, weight) Adds a new, weighted,
directed edge to the graph that connects two vertices.
getVertex(vertKey) finds the vertex in the graph named vertKey.
getVertices() returns the list of all vertices in the graph.
in returns True for a statement of the form vertex in graph, if the
given vertex is in the graph, False otherwise.
Types of Graph
A graph data structure is made up of a finite and potentially mutable set of vertices (also
known as nodes or points), as well as a set of unordered pairs for an undirected graph or
a set of ordered pairs for a directed graph. These pairs are recognized as edges, links, or
lines in a directed graph but are also known as arrows or arcs. The vertices could be
internal graph elements or external items represented by integer indices or references.
So depending upon the position of these nodes and vertices, there are different types of
graphs, such as:
Null Graph
Trivial Graph
Non-directed Graph
Directed Graph
Connected Graph
Disconnected Graph
Regular Graph
Types of Graph
Complete Graph
Cycle Graph
Cyclic Graph
Acyclic Graph
Finite Graph
Infinite Graph
Bipartite Graph
Planar Graph
Simple Graph
Multi Graph
Pseudo Graph
Euler Graph
Hamiltonian Graph
Types of Graph
Null Graph
The Null Graph is also known as the order zero graph. The term "null graph" refers to a
graph with an empty edge set. In other words, a null graph has no edges, and the null
graph is present with only isolated vertices in the graph.
The image displayed above is a null or zero graphs because it has zero edges between
the three vertices of the graph.
Types of Graph
Trivial Graph
A graph is called a trivial graph if it has only one vertex present in it. The trivial graph is
the smallest possible graph that can be created with the least number of vertices that is
one vertex only.
The above is an example of a trivial graph having only a single vertex in the whole
graph named vertices A.
Types of Graph
Non-Directed Graph
A graph is called a non-directed graph if all the edges present between any graph nodes
are non-directed. By non-directed edges, we mean the edges of the graph that cannot be
determined from the node it is starting and at which node it is ending. All the edges for a
graph need to be non-directed to call it a non-directed graph. All the edges of a non-
directed graph don't have any direction.
The graph that is displayed above is an example of a disconnected graph. This graph is
called a disconnected graph because there are four vertices named vertex A, vertex B,
vertex C, and vertex D. There are also exactly four edges between these vertices of the
graph. And all the vertices that are present between the different nodes of the graph are
not directed, which means the edges don't have any specific direction.
Types of Graph
Directed Graph
Another name for the directed graphs is digraphs. A graph is called a directed graph or
digraph if all the edges present between any vertices or nodes of the graph are directed
or have a defined direction. By directed edges, we mean the edges of the graph that have
a direction to determine from which node it is starting and at which node it is ending.
Types of Graph
Connected Graph
For a graph to be labelled as a connected graph, there must be at least a single path
between every pair of the graph's vertices. In other words, we can say that if we start
from one vertex, we should be able to move to any of the vertices that are present in that
particular graph, which means there exists at least one path between all the vertices of
the graph.
The graph shown above is an example of a connected graph because we start from any
one of the vertices of the graph and start moving towards any other remaining vertices
of the graph. There will exist at least one path for traversing the graph.
Types of Graph
Disconnected Graph
A graph is said to be a disconnected graph where there does not exist any path between
at least one pair of vertices. In other words, we can say that if we start from any one of
the vertices of the graph and try to move to the remaining present vertices of the graph
and there exists not even a single path to move to that vertex, then it is the case of the
disconnected graph. If any one of such a pair of vertices doesn't have a path between
them, it is called a disconnected graph.
The graph shown above is a disconnected graph. The above graph is called a
disconnected graph because at least one pair of vertices doesn't have a path to traverse
starting from either node.
Types of Graph
Regular Graph
For a graph to be called a regular, it should satisfy one primary condition: all graph
vertices should have the same degree. By the degree of vertices, we mean the number of
nodes associated with a particular vertex. If all the graph nodes have the same degree
value, then the graph is called a regular graph. If all the vertices of a graph have the
degree value of 6, then the graph is called a 6-regular graph. If all the vertices in a graph
are of degree 'k', then it is called a "k-regular graph“.
The graphs that are displayed above are regular graphs. In graph 1, there are three
vertices named vertex A, vertex B, and vertex C, All the vertices in graph 1, have the
degree of each node as 2. The degree of each vertex is calculated by counting the
number of edges connected to that particular vertex.
Types of Graph
Complete Graph
A graph is said to be a complete graph if, for all the vertices of the graph, there exists an
edge between every pair of the vertices. In other words, we can say that all the vertices
are connected to the rest of all the vertices of the graph. A complete graph of 'n' vertices
contains exactly nC2 edges, and a complete graph of 'n' vertices is represented as Kn.
for graph K4, there are four nodes named vertex E, vertex F, vertex G, and vertex H. For
example, the vertex F has three edges connected to it to connect it to the respective three
remaining vertices of the graph. Likewise, for the other three reaming vertices, there are
three edges associated with each one of them. As all the vertices of this graph have a
separate edge for other vertices, it is called a complete graph.
Types of Graph
Cycle Graph
If a graph with many vertices greater than three and edges form a cycle, then the graph
is called a cycle graph. In a graph of cycle type, the degree of all the vertices of the
cycle graph will be 2.
Types of Graph
Cyclic Graph
For a graph to be called a cyclic graph, it should consist of at least one cycle. If a graph
has a minimum of one cycle present, it is called a cyclic graph.
The graph shown in the image has two cycles present, satisfying the required condition
for a graph to be cyclic, thus making it a cyclic graph.
Types of Graph
Acyclic Graph
A graph is called an acyclic graph if zero cycles are present, and an acyclic graph is the
complete opposite of a cyclic graph.
The graph shown in the above image is acyclic because it has zero cycles present in it.
That means if we begin traversing the graph from vertex B, then a single path doesn't
exist that will traverse all the vertices and end at the same vertex that is vertex B.
Types of Graph
Finite Graph
If the number of vertices and the number of edges that are present in a graph are finite in
number, then that graph is called a finite graph.
The graph shown in the above image is the finite graph. There are four vertices named
vertex A, vertex B, vertex C, and vertex D, and the number of edges present in this
graph is also four, as both the number of nodes and vertices of this graph is finite in
number it is called a finite graph.
Types of Graph
Infinite Graph
If the number of vertices in the graph and the number of edges in the graph are infinite
in number, that means the vertices and the edges of the graph cannot be counted, then
that graph is called an infinite graph.
As we can see in the above image, the number of vertices in the graph and the number
of edges in the graph are infinite, so this graph is called an infinite graph.
Types of Graph
Bipartite Graph:
For a graph to be a Bipartite graph, it needs to satisfy some of the basic preconditions.
These conditions are:
All the vertices of the graph should be divided into two distinct sets of vertices X and Y.
All the vertices present in the set X should only be connected to the vertices present in
the set Y with some edges. That means the vertices present in a set should not be
connected to the vertex that is present in the same set.
Both the sets that are created should be distinct that means both should not have the
same vertices in them.
The graph shown in the above image can be drawn in a single plane with any two edges
intersecting. Thus it is a planar graph.
Types of Graph
Simple Graph
A graph is said to be a simple graph if the graph doesn't consist of no self-loops and no
parallel edges in the graph.
We have three vertices and three edges for the graph that is shown in the above image.
This graph has no self-loops and no parallel edges; therefore, it is called a simple graph.
Types of Graph
Multi Graph
A graph is said to be a multigraph if the graph doesn't consist of any self-loops, but
parallel edges are present in the graph. If there is more than one edge present between
two vertices, then that pair of vertices is said to be having parallel edges.
we can say that if two vertices of a graph are connected with more than one edge in a
graph, then it is said to be having parallel edges, thus making it a multigraph.
Types of Graph
Pseudo Graph
If a graph consists of no parallel edges, but self-loops are present in a graph, it is called
a pseudo graph. The meaning of a self-loop is that there is an edge present in the graph
that starts from one of the graph's vertices, and if that edge ends on the same vertex,
then it is called a pseudo graph.
Types of Graph
Euler Graph
If all the vertices present in a graph have an even degree, then the graph is known as an
Euler graph. By degree of a vertex, we mean the number of edges that are associated
with a vertex. So for a graph to be an Euler graph, it is required that all the vertices in
the graph should be associated with an even number of edges.
In the graph shown in the above image, we have five vertices named vertex A, vertex B,
vertex C, vertex D and vertex E. All the vertices except vertex C have a degree of 2,
which means they are associated with two edges each of the vertex. At the same time,
vertex C is associated with four edges, thus making it degree 4. The degree of vertex C
and other vertices is 4 and 2, respectively, which are even. Therefore, the graph
displayed above is an Euler graph.
Types of Graph
Hamilton Graph
Suppose a closed walk in the connected graph that visits every vertex of the graph
exactly once (except starting vertex) without repeating the edges. Such a graph is called
a Hamiltonian graph, and such a walk is called a Hamiltonian path. The Hamiltonian
circuit is also known as Hamiltonian Cycle.
in other words, A Hamiltonian path that starts and ends at the same vertex is called a
Hamiltonian circuit. Every graph that contains a Hamiltonian circuit also contains a
Hamiltonian path, but vice versa is not true. There may exist more than one Hamiltonian
path and Hamiltonian circuit in a graph.
Representation of Graph
ln graph theory, a graph representation is a technique to store graph into the memory of
computer.
To represent a graph, we just need the set of vertices, and for each vertex the neighbors
of the vertex (vertices which is directly connected to it by an edge).
If it is a weighted graph, then the weight will be associated with each edge.
There are different ways to optimally represent a graph, depending on the density of its
edges, type of operations to be performed and ease of use.
Adjacency Matrix
Incidence matrix
Adjacency List
Adjacency Matrix
Adjacency matrix is a sequential representation.
It is used to represent which nodes are adjacent to each other. i.e. is there any edge
connecting nodes to a graph.
In this representation, we have to construct a n X n matrix
A. If there is any edge from a vertex i to vertex j, then the corresponding element of A, a
i,j = 1, otherwise a i,j=0
If there is any weighted graph then instead of 1s and 0s, we can store the weight of the
edge
An adjacency matrix is also called as connection matrix. Sometimes it is also called a
Vertex matrix.
Adjacency Matrix
Adjacency Matrix Representation
If an Undirected Graph G consists of n vertices then the adjacency matrix of a graph is n
x n matrix A = [aij] and defined by -
aij = 1 {if there is a path exists from Vi to Vj}
aij = 0 {Otherwise}
Let's see some of the important points with respect to the adjacency matrix.
If there exists an edge between vertex Vi and Vj, where i is a row, and j is a column,
then the value of aij = 1.
If there is no edge between vertex Vi and Vj, then the value of aij = 0.
If there are no self loops in the simple graph, then the vertex matrix (or adjacency
matrix) should have 0s in the diagonal.
An adjacency matrix is symmetric for an undirected graph. It specifies that the value in
the ith row and jth column is equal to the value in jth row ith
If the adjacency matrix is multiplied by itself, and if there is a non-zero value is present
at the ith row and jth column, then there is the route from Vi to Vj with a length
equivalent to 2. The non-zero value in the adjacency matrix represents that the number
Adjacency Matrix
Adjacency matrix for an undirected graph
In an undirected graph, edges are not associated with the directions with them. In an
undirected graph, if there is an edge exists between Vertex A and Vertex B, then the
vertices can be transferred from A to B as well as B to A.
Let us consider the below-undirected graph and try to construct the adjacency matrix of
it.
In the graph, we can see there is no self-loop, so the diagonal entries of the adjacent
matrix will be 0. The adjacency matrix of the above graph will be
Adjacency Matrix
Adjacency matrix for a directed graph
In a directed graph, edges form an ordered pair. Edges represent a specific path from
some vertex A to another vertex B. Node A is called the initial node, while node B is
called the terminal node.
Let us consider the below directed graph and try to construct the adjacency matrix of it.
In the above graph, we can see there is no self-loop, so the diagonal entries of the
adjacent matrix will be 0. The adjacency matrix of the above graph will be
Adjacency Matrix
Q. What will be the adjacency matrix for the below undirected weighted graph?
Incidence matrix
In Incidence matrix representation, graph can be represented using a matrix of size:
Total number of vertices by total number of edges.
It means if a graph has 4 vertices and 6 edges, then it can be represented using a matrix
of 4X6 class. In this matrix, columns represent edges and rows represent vertices.
This matrix is filled with either 0 or 1 or -1. Where,
0 is used to represent row edge which is not connected to column vertex.
1 is used to represent row edge which is connected as outgoing edge to column vertex.
-1 is used to represent row edge which is connected as incoming edge to column vertex
Adjacency matrix
Example: Consider the multigraph shown in Fig, Determine its adjacency matrix.
Solution: Since the multigraph consist of five vertices. Therefore the adjacency matrix
will be an 5 x 5 matrix. The adjacency matrix of the multigraph is as follows:
Incidence matrix
Consider the undirected graph G as shown in fig. Find its incidence matrix Mi
The undirected graph consists of four vertices and five edges. Therefore, the incidence
matrix is an 4 x 5 matrix, which is shown in Fig:
Adjacency list
In adjacency list is used in the linked representation to store the Graph in the computer's
memory. It is efficient in terms of storage as we only have to store the values for edges.
An adjacency list is maintained for each node present in the graph, which stores the
node value and a pointer to the next adjacent node to the respective node. If all the
adjacent nodes are traversed, then store the NULL in the pointer field of the last node of
the list.
The sum of the lengths of adjacency lists is equal to twice the number of edges present
in an undirected graph.
Adjacency list
For a directed graph, the sum of the lengths of adjacency lists is equal to the number of
edges present in the graph.
In the case of a weighted directed graph, each node contains an extra field that is called
the weight of the node.
In an adjacency list, it is easy to add a vertex. Because of using the linked list, it also
saves space.
Transitive Closure
Transitive Closure it the reachability matrix to reach from vertex u to vertex v of a
graph. One graph is given, we have to find a vertex v which is reachable from another
vertex u, for all vertex pairs (u, v).
The final matrix is the Boolean type. When there is a value 1 for vertex u to vertex v, it
means that there is at least one path from u to v.
The matrix of transitive closure
1111
1111
1111
0001
Transitive Closure
Transitive Closure
Application of Graph
Graphs are used to define the flow of computation.
Graphs are used to represent networks of communication and data organization.
In Electrical Engineering, graph theory is used in designing of circuit connections.
In physics and chemistry, graph theory is used to study molecules.
In computer network, the relationships among interconnected computers ,within the
network, follow the principles of graph theory
Nodes in biological networks represent bimolecular such as genes, proteins or
metabolites, and edges connecting these nodes indicate functional, physical or
chemical interactions between the corresponding bimolecular.
Graphs are used to represent the routes between the cities. With the help of tree that
is a type of graph, we can create hierarchical ordered information such as family tree.
Graph Traversal
Graph traversal is a technique used to search for a vertex in a graph.
It is also used to decide the order of vertices to be visited in the search process.
A graph traversal finds the edges to be used in the search process without creating loops.
This means that, with graph traversal, we can visit all the vertices of the graph without
getting into a looping path.
There are two graph traversal techniques:
DFS (depth first search)
BFS (breadth first search)
Graph Traversal
DFS (depth first search)
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a
stack.
Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up
all the vertices from the stack, which do not have adjacent vertices.)
Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.
Example : Consider the following graph
Graph Traversal
DFS (depth first search)
Graph Traversal
DFS (depth first search)
Graph Traversal
DFS (depth first search)
Graph Traversal
DFS (depth first search)
As C does not have any unvisited adjacent node so we keep popping the stack until we
find a node that has an unvisited adjacent node. In this case, there's none and we keep
popping until the stack is empty.
Graph Traversal
BFS (Breadth first search)
Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and
uses a queue to remember to get the next vertex to start a search, when a dead end
occurs in any iteration.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a
queue.
Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
Example : Consider the following graph
Graph Traversal
Graph Traversal
Graph Traversal
BFS (Breadth first search)
At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm
we keep on dequeuing in order to get all unvisited nodes. When the queue gets emptied,
the program is over.
Minimum Spanning Tree
A spanning tree of an undirected graph G is a subgraph of G that is a tree containing all
the vertices of G.
A minimum spanning tree (MST) for a weighted undirected graph is a spanning tree
with minimum weight.
A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the
edges of a connected, edge-weighted undirected graph that connects all the vertices
together, without any cycles and with the minimum possible total edge weight.
That is, it is a spanning tree whose sum of edge weights is as small as possible
A minimum spanning tree has (V - 1) edges where V is the number of vertices in the
given graph.
Spanning tree cannot be disconnected.
Minimum Spanning Tree
Kruskal’s Algorithm:
Kruskal's Algorithm builds the spanning tree by adding edges one by one into a growing
spanning tree.
Kruskal's algorithm follows greedy approach as in each iteration it finds an edge which
has least weight and add it to the growing spanning tree.
Algorithm Steps:
Sort the graph edges with respect to their weights.
Start adding edges to the MST from the edge with the smallest weight until the edge of
the largest weight.
Only add edges which doesn't form a cycle.
Now, sort the edges given above in the ascending order of their weights.
Step 1 - First, add the edge AB with weight 1 to the MST. (draw tree here)
Step 2 - Add the edge DE with weight 2 to the MST as it is not creating the cycle.
Step 3 - Add the edge BC with weight 3 to the MST, as it is not creating any cycle or loop.
Step 4 - Now, pick the edge CD with weight 4 to the MST, as it is not forming the cycle.
Step 5 - After that, pick the edge AE with weight 5. Including this edge will create the cycle, so
discard it.
Step 6 - Pick the edge AC with weight 7. Including this edge will create the cycle, so discard it.
Step 7 - Pick the edge AD with weight 10. Including this edge will also create the cycle, so
discard it.
Minimum Spanning Tree: Prim’s Algorithm
The algorithm starts with an empty spanning tree. The idea is to maintain two sets of
vertices. The first set contains the vertices already included in the MST, and the other
set contains the vertices not yet included. At every step, it considers all the edges that
connect the two sets and picks the minimum weight edge from these edges. After
picking the edge, it moves the other endpoint of the edge to the set containing MST.
The working of Prim’s algorithm can be described by using the following steps:
Step 1: Determine an arbitrary vertex as the starting vertex of the MST.
Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST
(known as fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
Step 6: Return the MST and exit
Find the minimum spanning tree using Prim’s Algorithm
Find the minimum spanning tree using Prim’s Algorithm
Total cost= ?
Shortest Path problem
In graph theory, the shortest path problem is the problem of finding a path between two
vertices (or nodes) in a graph such that the sum of the weights of its constituent edges is
minimized.
The problem of finding the shortest path between two intersections on a road map may
be modeled as a special case of the shortest path problem in graphs,
where the vertices correspond to intersections and the edges correspond to road
segments, each weighted by the length of the segment.
Dijkstra’s Algorithm(shortest path)
It is a greedy algorithm that solves the single-source shortest path problem for a directed
graph G = (Y, E) with non-negative edge weights, i.e., w (u, v) > 0 for each edge (u, v)
EE.
Dijkstra's Algorithm maintains a set S of vertices whose final shortest - path weights
from the source s have already been determined. That's for all vertices v E S; we have d
[v] = δ (s, v).
The algorithm repeatedly selects the vertex u E V - S with the minimum shortest - path
estimate, insert u into S and relaxes all edges leaving u.
Because it always chooses the "lightest" or "closest" vertex in V - S to insert into set S,
it is called as the greedy strategy
Dijkstra’s Algorithm(shortest path)
The very first step is to mark all nodes as unvisited,
Mark the picked starting node with a current distance of O and the rest nodes with
infinity,
Now, fix the starting node as the current node,
for the current node, analyze all of its unvisited neighbors and measure their
distances by adding the current distance of the current node to the weight of the edge
that connects the neighbor node and current node,
Compare the recently measured distance with the current distance assigned to the
neighboring node and make it as the new current distance of the neighboring node,
After that, consider all of the unvisited neighbors of the current node, mark the
current node as visited,
If the destination node has been marked visited then stop, an algorithm has ended,
and
Else, choose the unvisited node that is marked with the least distance, fix it as the
new current node, and repeat the process again from step 4.
Dijkstra’s Example
Dijkstra’s Example