A Graph 2
A Graph 2
A graph is a
collection of a set of vertices and edges (formed by connecting two vertices). A graph is
defined as G = {V, E} where V is the set of vertices and E is the set of edges.
Graphs: can be defined as the pictorial representation of the set of elements (represented by
vertices) connected by the links known as edges. A graph is different from a tree in the sense
that a graph can have a cycle while a tree cannot have one.
A Graph G = (V, E) is a collection of sets V and E where V is a collection of vertices and E is
a collection of edges.
NW: A tree is a special type of graph.
Graphs can be used to model a wide variety of real-world problems, including social
networks, transportation networks, and communication networks. They can be represented in
various ways, such as by a set of vertices and a set of edges, or by a matrix or an adjacency
list. The two most common types of graphs are directed and undirected graphs.
Terminologies of Graphs:
.An edge is one of the two primary units used to form graphs. Each edge has two ends, which
are vertices to which it is attached.
If two vertices are endpoints of the same edge, they are adjacent.
.A vertex’s outgoing edges are directed edges that point to the origin.
.A vertex’s incoming edges are directed edges that point to the vertex’s destination.
.The total number of edges occurring to a vertex in a graph is its degree.
.A vertex with an in-degree of zero is referred to as a source vertex, while one with an out-
degree of zero is known as sink vertex.
.A path is a set of alternating vertices and edges, with each vertex connected by an edge.
.The path that starts and finishes at the same vertex is known as a cycle.
.A path with unique vertices is called a simple path.
.A spanning subgraph that is also a tree is known as a spanning tree.
.A connected component is the unconnected graph’s most connected subgraph.
.A bridge, which is an edge of removal, would sever the graph.
.Forest is a graph without a cycle.
Graph Representation:
Graph can be represented in the following ways:
1. Set Representation: Set representation of a graph involves two sets: Set of vertices V = {V1 ,
V2, V3, V4} and set of edges E = {{V1, V2}, {V2, V3}, {V3, V 4}, {V4 , V1}}. This representation
is efficient for memory but does not allow parallel edges.
2. Sequential Representation: This representation of a graph can be represented by means of
matrices: Adjacency Matrix, Incidence matrix and Path matrix.
• Adjacency Matrix: This matrix includes information about the adjacent nodes. Here, aij =
1 if there is an edge from Vi to V j otherwise 0. It is a matrix of order V×V.
• Incidence Matrix: This matrix includes information about the incidence of edges on the
nodes. Here, aij = 1 if the jth edge Ej is incident on ith vertex Vi otherwise 0. It is a matrix of
order V×E.
• Path Matrix: This matrix includes information about the simple path between two vertices.
Here, Pij = 1 if there is a path from Vi to Vj otherwise 0. It is also called as reachability matrix
of graph G.
3. Linked Representation: This representation gives the information about the nodes to which
a specific node is connected i.e. adjacency lists. This representation gives the adjacency lists
of the vertices with the help of array and linked lists. In the adjacency lists, the vertices which
are connected with the specific vertex are arranged in the form of lists which is connected to
that vertex.
Real-Time Applications of Graph:
• Social media analysis: Social media platforms generate vast amounts of data in real-time,
which can be analyzed using graphs to identify trends, sentiment, and key influencers. This can
be useful for marketing, customer service, and reputation management.
• Network monitoring: Graphs can be used to monitor network traffic in real-time, allowing
network administrators to identify potential bottlenecks, security threats, and other issues. This
is critical for ensuring the smooth operation of complex networks.
• Financial trading: Graphs can be used to analyze real-time financial data, such as stock
prices and market trends, to identify patterns and make trading decisions. This is particularly
important for high-frequency trading, where even small delays can have a significant impact
on profits.
• Internet of Things (IoT) management: IoT devices generate vast amounts of data in real-
time, which can be analyzed using graphs to identify patterns, optimize performance, and detect
anomalies. This is important for managing large-scale IoT deployments.
• Autonomous vehicles: Graphs can be used to model the real-time environment around
autonomous vehicles, allowing them to navigate safely and efficiently. This requires real-time
data from sensors and other sources, which can be processed using graph algorithms.
• Disease surveillance: Graphs can be used to model the spread of infectious diseases in real-
time, allowing health officials to identify outbreaks and implement effective containment
strategies. This is particularly important during pandemics or other public health emergencies.
• The best example of graphs in the real world is Facebook. Each person on Facebook is a node
and is connected through edges. Thus, A is a friend of B. B is a friend of C, and so on.
Advantages of Graph:
• Representing complex data: Graphs are effective tools for representing complex data,
especially when the relationships between the data points are not straightforward. They can
help to uncover patterns, trends, and insights that may be difficult to see using other methods.
• Efficient data processing: Graphs can be processed efficiently using graph algorithms,
which are specifically designed to work with graph data structures. This makes it possible to
perform complex operations on large datasets quickly and effectively.
• Network analysis: Graphs are commonly used in network analysis to study relationships
between individuals or organizations, as well as to identify important nodes and edges in a
network. This is useful in a variety of fields, including social sciences, business, and marketing.
• Pathfinding: Graphs can be used to find the shortest path between two points, which is a
common problem in computer science, logistics, and transportation planning.
• Visualization: Graphs are highly visual, making it easy to communicate complex data and
relationships in a clear and concise way. This makes them useful for presentations, reports, and
data analysis.
• Machine learning: Graphs can be used in machine learning to model complex relationships
between variables, such as in recommendation systems or fraud detection.
• Graphs are used in computer science to depict the flow of computation.
• Users on Facebook are referred to as vertices, and if they are friends, there is an edge
connecting them. The Friend Suggestion system on Facebook is based on graph theory.
• You come across the Resources Allocation Graph in the Operating System, where each process
and resource are regarded vertically. Edges are drawn from resources to assigned functions or
from the requesting process to the desired resources. A stalemate will develop if this results in
the establishment of a cycle.
• Web pages are referred to as vertices on the World Wide Web. Suppose there is a link from
page A to page B that can represent an edge. this application is an illustration of a directed
graph.
• Graph transformation systems manipulate graphs in memory using rules, Graph databases store
and query graph-structured data in a transaction-safe, permanent manner.
Disadvantages of Graph:
• Limited representation: Graphs can only represent relationships between objects, and not
their properties or attributes. This means that in order to fully understand the data, it may be
necessary to supplement the graph with additional information.
• Difficulty in interpretation: Graphs can be difficult to interpret, especially if they are large
or complex. This can make it challenging to extract meaningful insights from the data, and may
require advanced analytical techniques or domain expertise.
• Scalability issues: As the number of nodes and edges in a graph increases, the processing
time and memory required to analyze it also increases. This can make it difficult to work with
large or complex graphs.
• Data quality issues: Graphs are only as good as the data they are based on, and if the data is
incomplete, inconsistent, or inaccurate, the graph may not accurately reflect the relationships
between objects.
• Lack of standardization: There are many different types of graphs, and each has its own
strengths and weaknesses. This can make it difficult to compare graphs from different sources,
or to choose the best type of graph for a given analysis.
• Privacy concerns: Graphs can reveal sensitive information about individuals or
organizations, which can raise privacy concerns, especially in social network analysis or
marketing.
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are
sometimes also referred to as vertices and the edges are lines or arcs that connect any two
nodes in the graph. More formally a Graph can be defined as, A Graph consisting of a finite
set of vertices (or nodes) and a set of edges that connect a pair of nodes
1. Undirected Graphs: A graph in which edges have no direction, i.e., the edges do not
have arrows indicating the direction of traversal. Example: A social network graph where
friendships are not directional.
2. Directed Graphs: A graph in which edges have a direction, i.e., the edges have arrows
indicating the direction of traversal. Example: A web page graph where links between pages
are directional.
3. Weighted Graphs: A graph in which edges have weights or costs associated with
them. Example: A road network graph where the weights can represent the distance between
two cities.
4. Unweighted Graphs: A graph in which edges have no weights or costs associated
with them. Example: A social network graph where the edges represent friendships.
5. Complete Graphs: A graph in which each vertex is connected to every other vertex.
Example: A tournament graph where every player plays against every other player.
6. Bipartite Graphs: A graph in which the vertices can be divided into two disjoint sets
such that every edge connects a vertex in one set to a vertex in the other set. Example: A job
applicant graph where the vertices can be divided into job applicants and job openings.
7. Trees: A connected graph with no cycles. Example: A family tree where each person
is connected to their parents.
8. Cycles: A graph with at least one cycle. Example: A bike-sharing graph where the
cycles represent the routes that the bikes take.
9. Sparse Graphs: A graph with relatively few edges compared to the number of
vertices. Example: A chemical reaction graph where each vertex represents a chemical
compound and each edge represents a reaction between two compounds.
10. Dense Graphs: A graph with many edges compared to the number of vertices.
Example: A social network graph where each vertex represents a person and each edge
represents a friendship.
Types of Graphs:
1. Finite Graphs
A graph is said to be finite if it has a finite number of vertices and a finite number of edges. A
finite graph is a graph with a finite number of vertices and edges. In other words, both the
number of vertices and the number of edges in a finite graph are limited and can be counted.
Finite graphs are often used to model real-world situations, where there is a limited number of
objects and relationships between the
2. Infinite Graph:
A graph is said to be infinite if it has an infinite number of vertices as well as an infinite number
of edges.
3. Trivial Graph:
A graph is said to be trivial if a finite graph contains only one vertex and no edge. A trivial
graph is a graph with only one vertex and no edges. It is also known as a singleton graph or a
single vertex graph. A trivial graph is the simplest type of graph and is often used as a starting
point for building more complex graphs. In graph theory, trivial graphs are considered to be a
degenerate case and are not typically studied in detail
4. Simple Graph:
A simple graph is a graph that does not contain more than one edge between the pair of vertices.
A simple railway track connecting different cities is an example of a simple graph.
5. Multi Graph:
Any graph that contains some parallel edges but doesn’t contain any self-loop is called a
multigraph—for example a Road Map.
• Parallel Edges: If two vertices are connected with more than one edge then such edges are
called parallel edges that are many routes but one destination.
• Loop: An edge of a graph that starts from a vertex and ends at the same vertex is called a
loop or a self-loop.
6. Null Graph:
A graph of order n and size zero is a graph where there are only isolated vertices with no edges
connecting any pair of vertices.A null graph is a graph with no edges. In other words, it is a
graph with only vertices and no connections between them. A null graph can also be referred
to as an edgeless graph, an isolated graph, or a discrete graph
7. Complete Graph:
A simple graph with n vertices is called a complete graph if the degree of each vertex is n-1,
that is, one vertex is attached with n-1 edges or the rest of the vertices in the graph. A complete
graph is also called Full Graph.
8. Pseudo Graph:
A graph G with a self-loop and some multiple edges is called a pseudo graph. A pseudograph
is a type of graph that allows for the existence of loops (edges that connect a vertex to itself)
and multiple edges (more than one edge connecting two vertices). In contrast, a simple graph
is a graph that does not allow for loops or multiple edges.
9. Regular Graph:
A simple graph is said to be regular if all vertices of graph G are of equal degree. All complete
graphs are regular but vice versa is not possible. A regular graph is a type of undirected graph
where every vertex has the same number of edges or neighbors. In other words, if a graph is
regular, then every vertex has the same degree.
10. Bipartite Graph:
A graph G = (V, E) is said to be a bipartite graph if its vertex set V(G) can be partitioned into
two non-empty disjoint subsets. V1(G) and V2(G) in such a way that each edge e of E(G) has
one end in V1(G) and another end in V2(G). The partition V1 U V2 = V is called Bipartite of
G. Here in the figure: V1(G)={V5, V4, V3} and V2(G)={V1, V2}
So one of the spanning subgraphs can be as shown below G'(V’,E’). It has all the vertices of
the original graph G and some of the edges of G.
This is just one of the many spanning subgraphs of graph G. We can create various other
spanning subgraphs by different combinations of edges. Note that if we consider a graph
G'(V’,E’) where V’=V and E’=E, then graph G’ is a spanning subgraph of graph G(V,E).
Graph Operations:
The data appearing in our graphs are processed by means of certain operations. In fact, the
particular graph node that one chooses for a given situation depends largely in the frequency
with which specific operations are performed.
The following four operations play a major role in this text:
Traversing: accessing each record/node exactly once so that certain items in the record may be
processed. (This accessing and processing is sometimes called “visiting” the record.)
Searching: Finding the location of the desired node with a given key value, or finding the
locations of all such nodes which satisfy one or more conditions.
Inserting: Adding a new node/record to the structure.
Deleting: Removing a node/record from the structure.
We start from vertex 0, the BFS algorithm starts by putting it in the Visited list and putting all
its adjacent vertices in the stack.
Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since 0 has
already been visited, we visit 2 instead.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the back of the queue and visit
3, which is at the front of the queue.
Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is already visited. We visit
it.
Since the queue is empty, we have completed the Breadth First Traversal of the graph.
Depth First Search (DFS): Depth first traversal or Depth first Search is a recursive algorithm
for searching all the vertices of a graph or tree data structure.
DFS algorithm:
A standard DFS implementation puts each vertex of the graph into one of two categories:
1. Visited
2. Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
The DFS algorithm works as follows:
1. Start by putting any one of the graph's vertices on top of a stack.
2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to
the top of stack.
4. Keep repeating steps 2 and 3 until the stack is empty.
DFS example:
Let's see how the Depth First Search algorithm works with an example. We use an undirected
graph with 5 vertices.
We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all
its adjacent vertices in the stack.
Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has
already been visited, we visit 2 instead.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit
it.
After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have
completed the Depth First Traversal of the graph.
Program1:
#include <stdio.h>
int a[20][20], q[20], visited[20], n, i, j, f
= 0, r = -1;
void bfs(int v)
{
for(i = 1; i <= n; i++)
if(a[v][i] && !visited[i])
q[++r] = i;
if(f <= r)
{
visited[q[f]] = 1;
bfs(q[f++]);
}
}
void main()
{
int v;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d", &n);
for(i=1; i <= n; i++)
{
q[i] = 0;
visited[i] = 0;
}
printf("\n Enter graph data in matrix form:\n");
for(i=1; i<=n; i++)
{
for(j=1;j<=n;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\n Enter the starting vertex:");
scanf("%d", &v); bfs(v);
printf("\n The node which are reachable are:\n");
for(i=1; i <= n; i++)
{
if(visited[i])
printf("%d\t", i);
else
{
printf("\n Bfs is not possible. Not all nodes are reachable");
break;
}
}
getch();
}
Program2:
#include <stdio.h>
void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array
G[10][10]
void main()
{
int i,j; clrscr();
printf("Enter number of vertices:");
scanf("%d",&n); //read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
getch();
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}