Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit-V Graphs

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 24

UNIT-V

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

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

Example

The following is a graph with 5 vertices and 6 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)}.

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.

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 (startingVertex, endingVertex).

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.

1. Undirected Edge - An undirected egde 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).
2. Directed Edge - A directed egde is a uni-directional edge. If there is a directed edge between
vertices A and B then edge (A , B) is not equal to edge (B , A).

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

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:

A graph having a weight, or number, associated with each edge.

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:

An edge of a graph which starts and ends at the same 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.

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

A graph is said to be simple if there are no parallel and self-loop edges.

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

Total number of edges connected to a vertex is said to be degree of that vertex.

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

For example, let us consider the digraph shown in figure

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.

A path is simple if all vertices in the path are distinct.

Cyclic and Acyclic graph:


If there is a path containing one or more edges which starts from a vertex Vi and terminates into the
same vertex then the path is known as a cycle.

For example, there is a cycle in figure-1(a), figure-1(c) and figure-1(d).

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:

There are two ways of representing digraphs. They are:


 Adjacency matrix.
 Adjacency List.
 Incidence matrix

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.

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


Figure-5 Graph and its incidence matrix

Figure 5(b) shows the incidence matrix representation of the graph G1 shown in figure 5(a).

Traversing a Graph(Graph Traversals)

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

1. DFS (Depth First Search)


2. BFS (Breadth 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.

We use the following steps to implement DFS traversal...

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

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.

We use the following steps to implement BFS traversal...

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

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;
}

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");
getch();
}

Depth First Search (DFS) Program in C [Adjacency Matrix]

#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]);

//visited is initialized to zero


for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}

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);
}

Minimum Spanning Tree (MST):

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

Weight of a spanning tree w(T) is the sum of weights of all edges in T.

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:

 One practical application of a MST would be in the design of a network.

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.

 Another useful application of MST would be finding airline routes.

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:

1. Kruskal’s algorithm and


2. Prim’s algorithm.

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

Kruskal's algorithm works as follows:

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.

Kruskal’s Algorithm for minimal spanning tree is as follows:

1. Make the tree T empty.


2. Repeat the steps 3, 4 and 5 as long as T contains less than n - 1 edges and E is not
empty otherwise, proceed to step 6.
3. Choose an edge (v, w) from E of lowest cost.
4. Delete (v, w) from E.
5. If (v, w) does not create a cycle in T
then Add (v, w) to T
else discard (v, w)
6. If T contains fewer than n - 1 edges then print no spanning tree.
Example 1:
Construct the minimal spanning tree for the graph shown below:

Solution:

Arrange all the edges in the increasing order of their costs:

The stages in Kruskal’s algorithm for minimal spanning tree is as follows:


\\
PRIM'S ALGORITHM

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.

3. While mstSet doesn’t include all vertices

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:

The set mstSet is initially empty, i.e, mstSet ={ }

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

So mstSet becomes {0}.

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.

So mstSet now becomes mstSet={0, 1}.

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.

You might also like