Unit-V Graphs
Unit-V Graphs
Unit-V Graphs
Graphs
Introduction to Graphs:
Definition:
Graph is a non linear data structure, it contains set of vertices and set of edges which connects vertices
in the graph
Example
A graph is generally displayed above figure, in which the vertices are represented by circles and the
edges by lines.
Graph Properties:
Vertex
A individual data element of a graph is called as Vertex. Vertex is also known as node.
Edge
An edge is a connecting link between two vertices. Edge is also known as Arc.
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)).
Note: An edge with an orientation (i.e., arrow head) is a directed edge, while an edge with no
orientation is our undirected edge.
Undirected Graph
If all the edges in a graph are undirected, then the graph is an undirected graph.
Directed Graph
If all the edges are directed; then the graph is a directed graph
Weighted graph:
Connected Graph:
A graph is connected when there is a path between every pair of vertices. In a connected graph,
there are no unreachable vertices. A graph that is not connected is disconnected. A graph with just
one vertex is connected. A graph G is connected if and only if there is a simple path between any two
nodes in G.
Stongly connected :
A directed graph is said to be strongly connected if every vertex is reachable from every other vertex.
Self loop:
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.
In graph theory, multiple edges (also called parallel edges or a multi-edge), are two or more edges
that are incident to the same two vertices. A simple graph has no multiple edges.
Simple Graph
Complete Graph:
A graph G is said to be complete if every node is adjacent to every other node in G. A complete graph
with n nodes will have n(n-1)/2 edges.
Degree
Indegree
The number of incoming edges to a vertex v is called in–degree of the vertex (denote indeg(v)).
Outdegree
The number of outgoing edges from a vertex is called out-degree (denote outdeg(v)).
indegree(v1) = 2 outdegree(v1) = 1
indegree(v2) = 2 outdegree(v2) = 0
Path
A path is a trail in which all vertices (except perhaps the first and last ones) are distinct.
A trail is a walk in which all edges are distinct
A path is a sequence of vertices (v1, v2, . . . . . , vk), where for all i, (vi, vi+1) ε E.
If a graph (digraph) does not have any cycle then it is called acyclic graph.
Forest:
A Forest is a set of disjoint union of trees.
The following figure shows a forest F that consists of three trees T1, T2 and T3.
Multigraph:
A graph that has either self loop or parallel edges or both is called multi-graph.
Representation of Graphs:
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.
The adjacency matrix is also useful to store multigraph as well as weighted graph.
In case of multigraph representation, instead of entry 0 or 1, the entry will be between number of
edges between two vertices.
In case of weighted graph, the entries are weights of the edges between the vertices.
The adjacency matrix for a weighted graph is called as cost adjacency matrix. Figure-3(b) shows the
cost adjacency matrix representation of the graph G2 shown in Figure-3(a).
Fig-3 Weighted graph and its Cost adjacency matrix
Adjacency List
In this representation, every vertex of graph contains list of its adjacent vertices.
In this representation, the n rows of the adjacency matrix are represented as n linked lists.
An array Adj[1, 2, . . . . . n] of pointers where for 1 < v < n, Adj[v] points to a linked list containing
the vertices which are adjacent to v (i.e. the vertices that can be reached from v by a single edge).
If the edges have weights then these weights may also be stored in the linked list elements.
For the graph G in figure-4(a), the adjacency list in shown in figure-4 (b).
Figure-4 Adjacency matrix and adjacency list
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.
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.
Figure 5(b) shows the incidence matrix representation of the graph G1 shown in figure 5(a).
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 egdes to be used in the search process without creating loops that means
using graph traversal we visit all verticces of graph without getting into looping path.
There are two graph traversal techniques and they are as follows...
We use Stack data structure with maximum size of total number of vertices in the graph to
implement DFS traversal of a graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex and push it on to the
Stack. Mark the vertex as visited.
Step 3: Visit any one of the unvisited adjacent vertex of the verex which is at top of the stack
and push it on to the stack. Mark the vertex as visited.
Step 4: Repeat step 3 until there are no new adjacent 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 7: When stack becomes Empty, then produce final spanning tree by removing unused edges
from the graph
NOTE : Back tracking is coming back to the vertex from which we came to current vertex.
EXAMPLE:
BFS (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.
Step 2: Select any vertex as starting point for traversal. Visit that vertex V and insert it into the
Queue.
Step 3: Visit all the unvisited adjacent vertices to the vertex V(which is at front of the Queue)
and insert them into the Queue.
Step 4: When there is no new vertex to be visit from the vertex V at front of the Queue then
delete that vertex V from the Queue.
Step 6: When queue becomes Empty, then produce final spanning tree by removing unused edges
from the graph
Example:
Breadth first search (BFS) IN C:
#include<stdio.h>
#include<conio.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;
}
bfs(v);
#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;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
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);
}
A spanning tree for a connected graph is a tree whose vertex set is the same as the vertex set
of the given graph, and whose edge set is a subset of the edge set of the given graph. i.e., any
connected graph will have a spanning tree.
Hence, a spanning tree does not have cycles and it can not be disconnected.
A weighted graph is a graph, in which each edge has a weight (some real number).
Minimum spanning tree (MST) is a spanning tree with the smallest possible weight. A
Minimum Spanning Tree in an undirected connected weighted graph is a spanning Tree of
minimum weight (among all spanning trees).
Real-World examples on minimum spanning tree:
For instance, a group of individuals, who are separated by varying distances, wish to
be connected together in a telephone network. Although MST cannot do anything
about the distance from one connection to another, it can be used to determine the
least cost paths with no cycles in this network, thereby connecting everyone at a
minimum cost.
The vertices of the graph would represent cities, and the edges would represent routes
between the cities. MST can be applied to optimize airline routes by finding the least
costly paths with no cycles.
Minimum spanning tree, can be constructed using any of the following two algorithms:
Both algorithms differ in their methodology, but both eventually end up with the MST.
Kruskal's algorithm uses edges, and Prim’s algorithm uses vertex connections in determining
the MST
Kruskal’s Algorithm
This is a greedy algorithm. A greedy algorithm chooses some local optimum (i.e. picking an
edge with the least weight in a MST).
Take a graph with 'n' vertices, keep on adding the shortest (least cost) edge, while avoiding
the creation of cycles, until (n - 1) edges have been added. Sometimes two or more edges
may have the same cost.
The order in which the edges are chosen, in this case, does not matter. Different MST’s may
result, but they will all have the same total cost, which will always be the minimum cost.
Solution:
Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a connected weighted
undirected graph.
It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all
the edges in the tree is minimized.
This algorithm is directly based on the MST( minimum spanning tree) property.
Algorithm
1. Create a set mstSet that keeps track of vertices already included in MST.
2. Assign a key value to all vertices in the input graph. Initialize all key values as
INFINITE. Assign key value as 0 for the first vertex so that it is picked first.
a) Pick a vertex u which is not there in mstSet and has minimum key value.
b) Include u to mstSet.
c) Update key value of all adjacent vertices of u. To update the key values, iterate
through all adjacent vertices.
d) For every adjacent vertex v, if weight of edge u-v is less than the previous key
value of v, update the key value as weight of u-v
EXAMPLE:
Solution:
and keys assigned to vertices are key[]={0, INF, INF, INF, INF, INF, INF, INF} where INF indicates
infinite.
Now pick the vertex with minimum key value. The vertex 0 is picked, include it in mstSet
After including vertex ‘0’ to mstSet, update key values of adjacent vertices.
Adjacent vertices of ‘0’ are ‘1 and 7. The key values of 1 and 7 are updated as 4 and 8.
Following subgraph shows vertices and their key values, only the vertices with finite key values are
shown. The vertices included in MST are shown in green color.
Pick the vertex with minimum key value and not already included in MST (not in mstSET). The
vertex 1 is picked and added to mstSet.
Update the key values of adjacent vertices of 1. The key value of vertex 2 becomes 8.
Pick the vertex with minimum key value and not already included in MST (not in mstSET). We can
either pick vertex 7 or vertex 2, let vertex 7 is picked. So mstSet now becomes {0, 1, 7}. Update the
key values of adjacent vertices of 7. The key value of vertex 6 and 8 becomes finite (7 and 1
respectively).
Pick the vertex with minimum key value and not already included in MST (not in mstSET). Vertex 6 is picked.
So mstSet now becomes {0, 1, 7, 6}. Update the key values of adjacent vertices of 6. The key value of vertex 5
and 8 are updated.
We repeat the above steps until mstSet includes all vertices of given graph. Finally, we get the
following graph.