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

Chapter 11 - Graphs

Data Structures

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Chapter 11 - Graphs

Data Structures

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 23

CHAPTER - 11

GRAPHS
Introduction
Graph is a non linear data structure which 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 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.

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

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 1


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

Example: In the 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)).

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.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 2


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.

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.

Representation of Graphs in memory

Graph data structure is represented using following representations:

1) Adjacency Matrix

2) Incidence Matrix

3) Adjacency List

1) Adjacency Matrix

In this representation, graph can be represented using a matrix of size total number of vertices by
total number of vertices.

Example:

For a Undirected graph representation the adjacency matrix representation is

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 3


For a Directed graph representation the adjacency matrix representation is

That means if a graph with 4 vertices can be represented using a matrix of 4X4 class. In this
matrix, rows and columns both represent 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.

2) Incidence Matrix

In this representation, graph can be represented using a matrix of size total number of vertices by
total number of edges.

Example:

For a Directed graph representation the adjacency matrix representation is

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 4


That means if a graph with 4 vertices and 6 edges can be represented using a matrix of 4X6 class.
In this matrix, rows represent vertices and columns represent 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.

3) Adjacency List

In this representation, every vertex of graph contains list of its adjacent vertices.

Example: Consider the following directed graph representation implemented using linked list

This representation can also be implemented using array as follows:


Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 5
Operations on Graphs

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 vertices of graph without getting into looping path.

There are two graph traversal or graph searching techniques and they are as follows...

1) DFS (Depth First Search)

2) BFS (Breadth First Search)

1) DFS (Depth First Search)

In the Depth-first traversal, all of vertex’s descendents are processed before we move to an
adjacent vertex.

The depth-first traversal of a graph starts by processing the first vertex of the graph. After
processing the first vertex, we select any vertex adjacent to the first vertex and process it. As
each vertex is processed, we select an adjacent vertex until we reach a vertex with no adjacent
entries.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 6


For performing depth-first traversal a Stack is used where the traversal will process adjacent
vertices in descending LIFO order.

Method :

1) We begin the traversal by pushing the first vertex, into the stack.

2) We then loop, popping the stack and processing the vertex, pushing all of the adjacent vertices
into the stack.

3) When the stack is empty, the traversal is complete.

Each node in the graph g is processed using the STATUS variable. If STATUS=1 the node is
ready to be visited. If STATUS =2 the first node is removed from the stack and is currently being
processed and the adjacent nodes of the first node are pushed into the stack. Change the status of
the first node to STATUS = 3, which indicates that the processing of the first node is completed.

Algorithm DFS (Graph g)

// This algorithm traverses the graph ‘g’ using Depth first search traversal

1) Mark all the nodes to be visited and set the STATUS=1.

2) Start from the first node ‘N’ and set its STATUS=1 ready for processing and push it into the
stack.

3) Change the status of first node to STATUS=2 and remove the first node from the stack and
push all the adjacent nodes of the first node into the stack.

4) When the processing of the first node is completed change its STATUS = 3.

5) Repeat steps 3 and 4 until all the nodes of the graph are processed.

6) Print the nodes that are visited.

} // End of loop

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 7


Example:

2) BFS (Breadth First Search)

In the breadth-first traversal, all adjacent vertices are processed before processing the
descendents of a vertex i.e. before going to the next level.

We begin the traversal by picking a starting vertex and after processing it, we process all of its
adjacent vertices. When all of the adjacent vertices have been processed, we pick the first
adjacent vertex and process all of its vertices, then the second adjacent vertex and process all of
its vertices and so on until no vertex are to be processed.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 8


Method:

1) We begin by enqueuing the starting vertex in the queue.

2) We then loop, dequeuing the queue and processing the vertex from its adjacent vertices into
the queue.

3) When the queue is empty, the traversal is complete.

Each node in the graph g is processed using the STATUS variable. If STATUS=1 the node is
ready to be visited. If STATUS =2 the first node is removed from the queue and is currently
being processed and the adjacent nodes of the first node are inserted into the queue. Change the
status of the first node to STATUS = 3, which indicates that the processing of the first node is
completed.

Algorithm BFS (Graph g)

// This algorithm traverses the graph ‘g’ using Breadth first search traversal

1) Mark all the nodes to be visited and set the STATUS=1.

2) Start from the first node ‘N’ and set its STATUS=1 ready for processing and insert the node
into the queue.

3) Change the status of first node to STATUS=2 and remove the first node from the queue and
push all the adjacent nodes of the first node into the stack.

4) When the processing of the first node is completed change its STATUS = 3.

5) Repeat steps 2 to 5 until all the nodes of the graph are processed.

} // End of loop

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 9


Example:

Minimum Spanning tree

A Spanning tree is a sub-graph of G that has the same set of vertices of G and is a tree.

A Minimum spanning tree of a weighted connected graph G is its spanning tree of the smallest
weight, where the weight of a tree is defined as the sum of the weights on all its edges. The total
number of edges in Minimum spanning tree is V – 1 where V is the number of vertices.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 10


Example: For a given spanning graph G the spanning trees are given below:

Spanning tree with minimum cost is considered as Minimum spanning tree.

Minimum Spanning tree Algorithms

There are two algorithms for finding Minimum spanning tree

1) Prim’s algorithm

2) Kruskal’s algorithm

1) Prim’s algorithm

Prim’s algorithm is one of the methods to compute a Minimum spanning tree which uses a
greedy technique. This algorithm begins with a set U initialized to {1}.

In each stage, one node is picked as the root, and we add an edge, and thus an associated vertex,
to the tree, until all the vertices are present in the tree with V- 1 edges.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 11


At each step, it finds a shortest edge (u, v) such that the cost of (u, v) is the smallest among all
edges, where u is the Minimum spanning tree and V is not in Minimum spanning tree.

Algorithm

1) One node is picked as a root node (u) from the given connected graph.

2) At each stage choose a new vertex v from u, by considering an edge (u, v) with minimum cost
among all the edges from u, where u is already in the tree and v is not in the tree.

3) The Prim’s algorithm table is constructed with three parameters. They are:

Known – Vertex is added in the tree or not.

dv –Weight of the shortest arc connecting v to a known vertex.

Pv – last vertex which causes a change in dv

4) After selecting the vertex v, update rule is applied for each unknown w adjacent to v. The rule
is dw=Min (dw, Cw,v) that is if more than one path exist between v to w, then dw is updated with
minimum cost.

Example:

For the following graph construct Minimum spanning tree using Prim’s algorithm.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 12


Solution:

Step 1:

Step 2:

Here ‘A’ is taken as source vertex and marked as visited. Then the distance of its adjacent vertex
is updated as follows:

T[B].Dist = Min[T[B].Dist, Ca,b]

T[B].Dist = Min[∞,2]

T[B].Dist = 2

T[d].Dist = Min[T[d].Dist, Ca,b]

T[d].Dist = Min[∞,1]

T[d].Dist = 1

T[C].Dist = Min[T[C].Dist, Ca,b]

T[C].Dist = Min[∞,3]

T[C].Dist = 3

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 13


Step 3:

Next, vertex ‘D’ with minimum distance is marked as visited and the distance of its unknown
adjacent vertex is updated.

T[B].Dist = Min[T[B].Dist, Cd,b]

T[B].Dist = Min[2,2]

T[B].Dist = 2

T[C].Dist = Min[T[C].Dist, Cd,c]

T[C].Dist = Min[3,1]

T[C].Dist = 1

Step 4:

Next the vertex with minimum cost ‘C’ is marked as visited and the distance of its unknown
adjacent vertex is updated.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 14


Step 5:

Since there is no unknown vertex adjacent to ‘C’, there is no updation in the distance. Finally the
vertex ‘B’ which is not visited is marked.

The final Minimum spanning tree using Prim’s algorithm is as follows:

The minimum cost of this spanning tree is 4 i.e. Ca,b + Ca,d + Cc,d

2) Kruskal’s algorithm

Kruskal’s algorithm is another method to build the Minimum cost spanning tree.

Algorithm:

1) Start by selecting the two nodes with the minimal costing link.

2) Select any two nodes with the minimal costing link. Your selection is not bound by any
requirement to select nodes connected to previously selected nodes. Any two nodes we can
select, as long as it the minimal cost.

3) Repeat steps 1 and 2 until all nodes have been selected / connected.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 15


Example:

Solution:

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 16


Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 17
Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 18
SHORTEST PATH PROBLEM

The shortest path problem is the problem of finding a path between two vertices (or nodes) such
that the sum of the weights of its constituent edges is minimized.

Dijkstra developed a classic algorithm for the shortest path problem. The algorithm is known as

Dijkstra’s single source shortest path algorithm

Dijkstra’s algorithm is the prime example of greedy technique, which generally solves a problem
in stages. At each stage, it selects a vertex v, which has a smallest d v among all the unknown
vertices, and declares that the shortest path from S to V and mark it to be known. We should set
dw = dv + Cvw, if the new value for dw would be an improvement.

Algorithm

1) Create a table with known, Pv, dv parameters, where the size of the table equivalent to the
number of vertices 0 to N-1.

2) Read graph from the adjacency list representation.

3) Select a vertex V which has smallest d v among all unknown vertices and sets the shortest path
from S to V as known.

4) The adjacent vertices W to V is located and d w is set as dw = dv + Cvw, if the new sum is less
than the existing dw. In every stage dw is updated only if there is an improvement in the path
distance.

5) Repeat steps 3 and 4, until all vertices are classified under known.

Example:

Find the shortest path for the following weighted graph.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 19


Solution:

Step 1:

Step 2:

Vertex ‘A’ is chosen as source vertex and is declared as known vertex. Then the adjacent
vertices of ‘A’ is found and its distance are updated as follows:

T[B].Dist = Min[T[B].Dist, T[A].Dist + Ca,b]

T[B].Dist = Min[∞, 0+2]

T[B].Dist = 2

T[d].Dist = Min[T[d].Dist, T[a].Dist + Ca,d]

T[d].Dist = Min[∞, 0+1]

T[d].Dist = 1

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 20


Step 3:

Now, select the vertex with minimum distance, which is not known and mark that vertex as
visited. Here ‘D’ is the next minimum distance vertex. The adjacent vertex to ‘D’ is ‘C’,
therefore, the distance of C is updated as follows.

T[C].Dist = Min[T[C].Dist, T[D].Dist + Cd,c]

T[C].Dist = Min[∞, 1+1]

T[C].Dist = 2

Step 4:

The next minimum vertex is ‘B’ and mark it as visited.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 21


Step 5:

APPLICATIONS OF GRAPHS

Let us assume one input line containing 4 integers followed by any number of input lines with 2
integers each. The first integer on the first line, n, represents number of cities which are
numbered from 0 to n-1. The second and third integers on that line are between 0 to n-1 and
represent two cities. It is desired to travel from the first city to second using exactly nr roads,
where nr is the 4rth integer on the first input line. Each subsequent input line contains two
integers representing two cities, indicating that there is a road (path) from the first city to the
second. The problem is to determine whether there is a path of required length by which one can
travel from the first of the given cities to the second.

Following is the plan for the solution:

Create a graph with cities as nodes and the roads as arcs. To find the path of length nr from node
A to node B, look for a node C such that an arc exists from A to C and a path of length nr-1

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 22


exists from C to B. If these conditions are satisfied for some node C, the desired path exists. If
the conditions are not satisfied for any node C, the desired path does not exist.

The traversal of a graph like Depth first traversal has many important applications such as
findings the components of the graph, detecting cycles in an undirected graph, determining
whether the graph is bi-connected etc.

Prepared by Dr.B.GOPI, Asst. Professor, KIST, Kakutur, Nellore, A.P Page 23

You might also like