0% found this document useful (0 votes)
74 views38 pages

Unit III - Graphs

Uploaded by

pec library
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views38 pages

Unit III - Graphs

Uploaded by

pec library
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.

E-CSE

UNIT III NON LINEAR DATA STRUCTURES - GRAPHS 9


Definition – Representation of Graph – Types of graph - Breadth-first traversal – Depth -
first traversal – Topological Sort – Bi-connectivity – Cut vertex - Euler circuits -
Minimum Spanning Tree: Prim’s and Kruskal’s Algorithm – Single Source Shortest Path:
Dijkstra’s Algorithm. Applications of graphs.

DEFINITION
A Graph G = (V,E) consists of a set of vertices(V) and set of edges (E). Each edge is a
pair (v,w), where v,w € V. Edges are sometimes referred to as arcs.
Example:

V = { V1,V2,V3,V4}
E = {E1, E2, E3, E4 }
REPRESENTATION OF GRAPHS
The two commonly used representations of Graphs are:
1. Adjacency Matrix
2. Adjacency List
1. Adjacency Matrix
Consider a graph C of n vertices and the matrix M. If there is an edge present between
vertices Vi and Vj, then M[i][j] = 1 else M[i][j] = 0. For an undirected graph, M[i][j] =
M[i][j = 1.
An Adjacency Matrix Representation for Undirected Graph

23CS1302 1 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

An Adjacency Matrix Representation for Directed graph

Creating a Graph using Adjacency Matrix


Creation of graph using adjacency matrix is a simple task. The adjacency matrix is
nothing but a two dimensional array. The algorithm for creation of graph using adjacency
matrix is given below:

1) Declare an array of M [size][size] which stores the graph.


2) Enter the no. of nodes in the graph.
3) Enter the edges of the graph by two vertices each, say V i , Vj, which indicates the
edge.
4) If the graph is directed set M [i][j]= 1. If graph is undirected set M[i][j] =M[i][j]=1.
5) When all the edges for the desired graph is entered print the graph M[i][j].

1. Adjacency List
The type in which a graph is created with the linked list is called adjacency list. So all the
advantages of linked list can be obtained in this type of graph. We need not have a prior
knowledge of maximum number of nodes.

Construction of Adjacency List:


Since graph is a set of vertices and edges, we will maintain the two structures, for vertices
and edges respectively.
Consider the graph given below. It has vertices a,b,c,d & e.

23CS1302 2 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

The linked list representation of the head nodes and the adjacent nodes are given below.
Struct head
{
char data;
struct head *down;
struct head *next;
}
struct node
{
int ver;
struct node *link
}

TYPES OF GRAPHS
Graphs are classified into two types. They are:
i. Directed Graph.
ii. Undirected Graph.
i. Directed Graph: The directions are shown on the edges. Consider the graph given
below:
E1 V1
E2

V2 V3

E3 E4
V4

23CS1302 3 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

In the above graph, the edge E1 is in between the vertices V1 and V2. The Vertex V1 is
called the head and V2 is called the tail. It is also referred as digraph.

ii. Undirected Graph: In this type of graph, the edges are not directed.

. In this type of graph the edge E is

Graph Terminologies:

Weighted Graph: A Graph is said to be weighted graph if every edge in the graph is
assigned a weight or value.

Unweighted Graph: A Graph is said to be unweighted graph if the edge in the graph is
not assigned a weight or value
Complete graph: If an undirected graph of n vertices consists of n(n-1)/2 number of
edges then it is called as complete graph.
The graph shown below is a complete graph.

23CS1302 4 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Sub graph: A Sub graph G’ of graph G is a graph such that the set of vertices and
set of edges of G’ are proper subset of the set of edges of G.

Connected graph: An undirected graph is said to be connected if for every pair of


distinct vertices Vi and Vj in V(G) there is a path from Vi to Vj in G.

A directed graph with this property is called as strongly connected. If a directed graph
is not strongly connected, but the underlying graph is connected, then the graph is said to
be weekly connected.

Adjacency: Vertex w is adjacent to v if and only if (v, w)  E.

Length of a path: A path is a sequence of vertices w1, w2, w3, ..., wN, such that (wi, wi+1)
 E for 1 < i < N. The length of a path is the number of edges on the path, which is N-1.
A simple path is one such that all vertices are distinct, except that the first and the last
could be the same.
Cycle: A cycle in a directed graph is a path of length at least 1 such that w1 = wN.

Acyclic Graph: A directed graph is acyclic if it has no cycles (abbreviated as DAG).

23CS1302 5 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Indegree: The indegree of a vertex v is the number of edges entering into the vertex v.
Outdegree: The outdegree of a vertex v is the number of edges leaving the vertex v.

Example: Consider the graph given below:

The indegree of a is 0.
The outdegree of a is 2.

Graph Traversal:

There are two types of Graph Traversals. They are:


1. Breadth First Traversal also called as Breadth First Search (BFS)
2. Depth First Traversal also called as Depth First Search (DFS)

1. Breadth First Traversal also called as Breadth First Search (BFS)


In the BFS, a vertex V is taken visited first. Then the adjacent vertices of V are visited.
The same procedure is performed for all the vertices in the graph.

ALGORITHM
1. Create a graph.
2. Read the vertex from which you want to traverse the graph say V i.
3. Initialise the visited array to 1 at the index of V i
4. Insert the visited vertex Vi in the queue
5. Visit the vertex which is at the front of the queue. Delete it from the queue and place
its adjacent nodes in the queue.

23CS1302 6 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

6. Repeat the step 5, till the queue is not empty


7. Stop.
Explanation of logic of BFS

In BFS the queue is maintained for storing the adjacent nodes and an array “visited” is
maintained for keeping the track of visited nodes. i.e. once a particular t is visited it
should not be revisited again.

23CS1302 7 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

23CS1302 8 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Increment front, delete the node from Queue and print it.

So output will be - BPS for above graph as


1 2 3 4
Routine:

2. Depth First Traversal also called as Depth First Search (DFS)


In this method, we follow the path as deeply as we can go. When there is no adjacent
vertex present we traverse back and search for unvisited vertex. We will maintain a
visited array to mark all the visited vertices. In case of DFS the depth of a graph should
be known.

ALGORITHM
Step 1: Choose any node in the graph. Designate it as the search node and mark it as
visited.

23CS1302 9 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Step 2: Using the adjacency matrix of the graph, find a node adjacent to the search node
that has not been visited yet. Designate this as the new search node and mark it as visited.
Step 3: Repeat Step 2 using the new search node. If no node satisfying Step 2 can be
found, return to the previous search node and continue.
Step 4: When a return to the previous node in step 3 is impossible, the search from the
originally chosen search node is complete.
Step 5: If the graph still contains unvisited nodes, choose any node that has not been
visited and repeat Step 1 through Step 4.

Example:

In DFS the basic data structure for storing the adjacent vertices is stack.

Step 1: Start with vertex 1, print it so ‘1’ gets printed. Mark I as visited.

23CS1302 10 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Routine for DFS:

Void DFS(Vertex V)
{
visisted[V]=True;
for each W adjacent to V
if(!visisted[W])

23CS1302 11 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

DFS(W);
}
TOPOLOGICAL SORT

DEFINITION

A topological sort is an ordering of vertices in a directed acyclic graph, such that if there
is a path from vi to vj, then vj appears after vi in the ordering.

Topological ordering is not possible, if the graph has a cycle, since for two vertices v and
w in a cycle, v precedes w and w precedes v.

Implementation of Topological Sort


Algorithm:
1. Find the indegree for every vertex.
2. Place the vertices whose indegree is ‘0’ on the empty queue.
3. Dequeue the vertex V and decrement the indegree’s of all its adjacent vertices.
4. Enqueue the vertex on the queue, if its indegree falls to zero.
5. Repeat from step 3 until the queue becomes empty.
6. The topological ordering is the order in which the vertices dequeued.
Consider the graph given below:

Step 1
Number of l’s present in each column of adjacency matrix represents the indegree of
corresponding vertex. In the given graph, indegree of a = 0, b=1, c=2 and d=2.

23CS1302 12 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Step 2
Enqueue the vertex, whose indegree is ‘0’
Since vertex ‘a’ is 0, so place it on the queue.
Step 3
Dequeue the vertex ‘a’ from the queue and decrement the indegree’s of its adjacent
vertex’
Step 4
Dequeue the vertex ‘b’ from Q and decrement the indegree’s of its adjacent vertex.
Step 5
Dequeue the vertex c’ from Q and decrement the indegree’s of its adjacent vertex..
Step 6
Dequeue the vertex ‘d’.

The topological sort for the graph is the vertices which are dequeued is shown below.

The topological ordering is a b c d

Consider another example given below:

23CS1302 13 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

The topological ordering is V1, V2, V5, V4, V3, V7, V6.

Routine to perform Topological Sort

23CS1302 14 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

void Topsort (Graph G)


{
Queue Q
mt counter = 0;
Vertex V, W;
Q = CreateQueue (NumVertex); Makeempty (Q); for each vertex V
if(indegree [ = = 0)
Enqueue (V, Q);
while (! IsEmpty (Q))
{
V = Dequeue (Q); TopNum [ = + + counter; for each W adjacent to V
if (--Indegree [ = = 0)
Enqueue (W, Q);
}
if (counter! = N% Vertex)
Error (“ Graph has a cycle”);
DisposeQueue (Q); 1 Free the Memory /
}

BICONNECTIVITY

A connected undirected graph is biconnected if there are no vertices whose


removal disconnects the rest of the graph.
If a graph is not biconnected, the vertices whose removal would disconnect the
graph are known as articulation points. These nodes are critical in many applications. The
graph given below is not biconnected. C and D are articulation points. The removal of
C would disconnect G, and the removal of D would disconnect E and F from the rest of
the graph.

23CS1302 15 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Consider the Graph given below:

23CS1302 16 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Properties of Biconnected Graph:


1. There are two disjoint paths between any two vertices.
2. There exists simple cycle between two vertices.
3. There should not be any cut vertex. Cut vertex is a vertex which, when removed
from the graph, the graph becomes disconnected.

EULER CIRCUITS
Definition:
An Eulerian path is a path in a graph which visits each edge exactly once. Similarly, an
Eulerian circuit is an Eulerian path which starts and ends on the same vertex. They were
first discussed by Leonhard Euler while solving the famous Seven Bridges of Königsberg
problem in 1736.

Mathematically the problem can be stated like this:

Given the graph on the right, is it possible to construct a path (or a cycle, i.e. a path
starting and ending on the same vertex) which visits each edge exactly once?

23CS1302 17 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Graphs which allow the construction of so called Eulerian circuits are called Eulerian
graphs. Euler observed that a necessary condition for the existence of Eulerian circuits is
that all vertices in the graph have an even degree, and that for an Eulerian path either all,
or all but two (i.e., the two endpoint) vertices have an even degree.
Sometimes a graph that has an Eulerian path, but not an Eulerian circuit (in other words,
it is an open path, and does not start and end at the same vertex) is called semi-Eulerian.

Graph 1 Graph 2

23CS1302 18 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Graph 3 Graph 4

Graph 5 Graph 6

What is the relationship between the nature of the vertices and the kind of path/circuit
that the graph contains?

Look at the table given below for the answer.

Graph Number of odd Number of even What does the


vertices (vertices vertices (vertices path contain?
connected to an connected to an (Euler path = P;
odd number of even number of Euler circuit = C;
edges) edges)
Neither = N)
1 0 10 C
2 0 6 C
3 2 6 P
4 2 4 P
5 4 1 N
6 8 0 N

From the above table, we can observe that:

1. A graph with all vertices being even contains an Euler circuit.


2. A graph with 2 odd vertices and some even vertices contains an Euler path.
3. A graph with more than 2 odd vertices does not contain any Euler path or circuit.

23CS1302 19 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Minimum spanning tree


Given a connected, undirected graph, a spanning tree of that graph is a subgraph that is a
tree and connects all the vertices together. A single graph can have many different
spanning trees.
We can also assign a weight to each edge, which is a number representing how
unfavorable it is, and use this to assign a weight to a spanning tree by computing the sum
of the weights of the edges in that spanning tree.
A minimum spanning tree (MST) or minimum weight spanning tree is then a
spanning tree with weight less than or equal to the weight of every other spanning tree.
More generally, any undirected graph (not necessarily connected) has a minimum
spanning forest, which is a union of minimum spanning trees for its connected
components.

There are mainly two algorithms exits to find Minimum spanning tree of any graph:
(i) Prims Algorithm
(ii) Kruskals Algorithm
Prim's algorithm
Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a
connected weighted undirected graph. This means it finds a subset of the edges that forms

23CS1302 20 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

a tree that includes every vertex, where the total weight of all the edges in the tree is
minimized.
The algorithm was developed in 1930 by Czech mathematician Vojtěch Jarník and later
independently by computer scientist Robert C. Prim in 1957 and rediscovered by Edsger
Dijkstra in 1959.
Therefore it is also sometimes called the DJP algorithm, the Jarník algorithm, or the
Prim–Jarník algorithm.
The only spanning tree of the empty graph (with an empty vertex set) is again the empty
graph. The following description assumes that this special case is handled separately.
The algorithm continuously increases the size of a tree, one edge at a time, starting with a
tree consisting of a single vertex, until it spans all vertices.

 Input: A non-empty connected weighted graph with vertices V and edges E (the
weights can be negative).
 Initialize: Vnew = {x}, where x is an arbitrary node (starting point) from V, Enew =
{}
 Repeat until Vnew = V:
o Choose an edge (u, v) with minimal weight such that u is in Vnew and v is
not (if there are multiple edges with the same weight, any of them may be
picked)
o Add v to Vnew, and (u, v) to Enew
 Output: Vnew and Enew describe a minimal spanning tree

EXAMPLE:

GRAPH Description

This is our original weighted graph. The numbers


near the edges indicate their weight.

23CS1302 21 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Vertex D has been arbitrarily chosen as a starting


point. Vertices A, B, E and F are connected to D
through a single edge. A is the vertex nearest to D
and will be chosen as the second vertex along with
the edge AD.

The next vertex chosen is the vertex nearest to either


D or A. B is 9 away from D and 7 away from A, E is
15, and F is 6. F is the smallest distance away, so we
highlight the vertex F and the arc DF.

The algorithm carries on as above. Vertex B, which


is 7 away from A, is highlighted.

In this case, we can choose between C, E, and G. C


is 8 away from B, E is 7 away from B, and G is 11
away from F. E is nearest, so we highlight the vertex
E and the arc BE.

Here, the only vertices available are C and G. C is 5


away from E, and G is 9 away from E. C is chosen,
so it is highlighted along with the arc EC.

23CS1302 22 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Vertex G is the only remaining vertex. It is 11 away


from F, and 9 away from E. E is nearer, so we
highlight it and the arc EG.

Now all the vertices have been selected and the


minimum spanning tree is shown in green. In this
case, it has weight 39.

U Edge(u,v) V\U
{} {A,B,C,D,E,F,G}
(D,A) = 5 V
(D,B) = 9
{D} {A,B,C,E,F,G}
(D,E) = 15
(D,F) = 6
(D,B) = 9
(D,E) = 15
{A,D} {B,C,E,F,G}
(D,F) = 6 V
(A,B) = 7
(D,B) = 9
(D,E) = 15
{A,D,F} (A,B) = 7 V {B,C,E,G}
(F,E) = 8
(F,G) = 11
{A,B,D,F} (B,C) = 8 {C,E,G}

23CS1302 23 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

(B,E) = 7 V
(D,B) = 9 cycle
(D,E) = 15
(F,E) = 8
(F,G) = 11
(B,C) = 8
(D,B) = 9 cycle
(D,E) = 15 cycle
{A,B,D,E,F} (E,C) = 5 V {C,G}
(E,G) = 9
(F,E) = 8 cycle
(F,G) = 11
(B,C) = 8 cycle
(D,B) = 9 cycle
(D,E) = 15 cycle
{A,B,C,D,E,F} {G}
(E,G) = 9 V
(F,E) = 8 cycle
(F,G) = 11
(B,C) = 8 cycle
(D,B) = 9 cycle
{A,B,C,D,E,F,G} (D,E) = 15 cycle {}
(F,E) = 8 cycle
(F,G) = 11 cycle

Kruskal's algorithm
Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree
for a connected weighted graph. This means 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. If the graph is not connected, then it finds a minimum spanning forest (a
minimum spanning tree for each connected component). Kruskal's algorithm is an
example of a greedy algorithm.

This algorithm first appeared in Proceedings of the American Mathematical Society, in


1956, and was written by Joseph Kruskal.

 Create a Spanning tree F (a set of vertices), where each vertex in the graph is a
separate tree.
 Create a set S containing all the edges in the graph and sort them in ascending
order.
 While S is nonempty and F is not yet spanning

23CS1302 24 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

o Remove an edge with minimum weight from S


o if that edge connects two different trees, then add it to the spanning tree,
combining two trees into a single tree
o Otherwise discard that edge.
 Repeat the above step until all the vertices are joined.

Example:

Graph Description

This is our original graph. The numbers near the arcs


indicate their weight. None of the arcs are
highlighted.

AD and CE are the shortest arcs, with length 5, and


AD has been arbitrarily chosen, so it is highlighted.

CE is now the shortest arc that does not form a


cycle, with length 5, so it is highlighted as the
second arc.

The next arc, DF with length 6, is highlighted using


much the same method.

23CS1302 25 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

The next-shortest arcs are AB and BE, both with


length 7. AB is chosen arbitrarily, and is highlighted.
The arc BD has been highlighted in red, because
there already exists a path (in green) between B and
D, so it would form a cycle (ABD) if it were chosen.

The process continues to highlight the next-smallest


arc, BE with length 7. Many more arcs are
highlighted in red at this stage: BC because it would
form the loop BCE, DE because it would form the
loop DEBA, and FE because it would form FEBAD.

Finally, the process finishes with the arc EG of


length 9, and the minimum spanning tree is found.
The total weight is 39.

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.
An example is finding the quickest way to get from one location to another on a road
map; in this case, the vertices represent locations and the edges represent segments of
road and are weighted by the time needed to travel that segment.

There are several variations according to whether the given graph is undirected, directed,
or mixed. For undirected graphs, the shortest path problem can be formally defined as
follows. Given a weighted graph (that is, a set V of vertices, a set E of edges, and a real-
valued weight function f : E → R), and elements v and v' of V, find a path P from v to a v'
of V so that

23CS1302 26 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

is minimal among all paths connecting v to v' .

The problem is also sometimes called the single-pair shortest path problem, to
distinguish it from the following variations:

 The single-source shortest path problem, in which we have to find shortest


paths from a source vertex v to all other vertices in the graph.
 The single-destination shortest path problem, in which we have to find shortest
paths from all vertices in the directed graph to a single destination vertex v. This
can be reduced to the single-source shortest path problem by reversing the arcs in
the directed graph.
 The all-pairs shortest path problem, in which we have to find shortest paths
between every pair of vertices v, v' in the graph.

the most important algorithms for solving this problem are:

 Dijkstra's algorithm solves the single-source shortest path problems.


 Bellman-Ford algorithm solves the single source problem if edge weights may be
negative.
 A* search algorithm solves for single pair shortest path using heuristics to try to
speed up the search.
 Floyd-Warshall algorithm solves all pairs shortest paths.
 Johnson's algorithm solves all pairs shortest paths, and may be faster than Floyd-
Warshall on sparse graphs.
 Perturbation theory finds (at worst) the locally shortest path.

Dijkstra's algorithm
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956
and published in 1959, is a graph search algorithm that solves the single-source shortest
path problem for a graph with nonnegative edge path costs, producing a shortest path
tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest
cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used
for finding costs of shortest paths from a single vertex to a single destination vertex by
stopping the algorithm once the shortest path to the destination vertex has been
determined.
For example, if the vertices of the graph represent cities and edge path costs represent
driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm

23CS1302 27 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

can be used to find the shortest route between one city and all other cities. As a result, the
shortest path first is widely used in network routing protocols, most notably IS-IS and
OSPF (Open Shortest Path First).

Dijkstra's original algorithm does not use a min-priority queue and runs in O(|V|2). The
idea of this algorithm is also given in (Leyzorek et al. 1957). The common
implementation based on a min-priority queue implemented by a Fibonacci heap and
running in O(|E| + |V| log |V|) is due to (Fredman & Tarjan 1984). This is asymptotically
the fastest known single-source shortest-path algorithm for arbitrary directed graphs with
unbounded nonnegative weights. (For an overview of earlier shortest path algorithms and
later improvements and adaptations, see: Single-source shortest-paths algorithms for
directed graphs with nonnegative weights.)

Algorithm
Let the node at which we are starting be called the initial node. Let the distance of node
Y be the distance from the initial node to Y. Dijkstra's algorithm will assign some initial
distance values and will try to improve them step by step.
1. Assign to every node a tentative distance value: set it to zero for our initial node
and to infinity for all other nodes.
2. Mark all nodes except the initial node as unvisited. Set the initial node as current.
Create a set of the unvisited nodes called the unvisited set consisting of all the
nodes except the initial node.
3. For the current node, consider all of its unvisited neighbors and calculate their
tentative distances. For example, if the current node A is marked with a distance
of 6, and the edge connecting it with a neighbor B has length 2, then the distance
to B (through A) will be 6+2=8. If this distance is less than the previously
recorded distance, then overwrite that distance. Even though a neighbor has been
examined, it is not marked as visited at this time, and it remains in the unvisited
set.
4. When we are done considering all of the neighbors of the current node, mark the
current node as visited and remove it from the unvisited set. A visited node will
never be checked again; its distance recorded now is final and minimal.
5. The next current node will be the node marked with the lowest (tentative)
distance in the unvisited set.

23CS1302 28 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

6. If the unvisited set is empty, then stop. The algorithm has finished. Otherwise, set
the unvisited node marked with the smallest tentative distance as the next "current
node" and go back to step 3.

In a given graph, and starting node, Dijkstra's Algorithm discovers the shortest
path from the starting node to all other nodes.

Assumptions: The cost/length of travelling between nodes is known.

The Explanation: Dijkstra's Algorithm

Table 1: Initial Entries for distances to nodes


from Node 'a'
Node Distance to Node from Node 'a'
b INFINTE
c INFINTE
d INFINTE
e INFINTE
f INFINTE
g INFINTE
h INFINTE
i INFINTE
Figure 1: Dijkstra - Initial Position
23CS1302 29 DATA STRUCTURES
PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Figure 1 displays the graph: nodes are black circles labelled a-f, a path is a black line
connecting two nodes, each path has an associated length beside it (the numbers). The
lengths are not to scale.

Node 'a' is our starting node, we want to find the shortest path to all other nodes in the
graph. To do this, we generate a table. This table has the distance to all the nodes in the
graph, from the perspective of the starting node 'a'.

As can be seen from Table 1, the initial entries for the distances are all set to infinity (or
some notional maximum value). This ensures that any path found will be shorter than the
initial value stored in the table.

The node 'a' is the starting node, as such we examine all the possible paths away from this
node first. The options are as follows:

Table 2: Distance to nodes (from 'a') accesible


from node 'a'
Node Distance to Node from Node 'a'
b 7
c 4
d 5

These values are used to update the graph table, Table 1, which becomes:

Table 3: Entries for distances to nodes from


Node 'a'
Node Distance to Node from Node 'a'
b 7
c 4
d 5
e INFINTE
f INFINTE
g INFINTE
h INFINTE
i INFINTE

23CS1302 30 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Figure 2: Dijkstra's algorithm

Figure 2 shows the routes marked in red.


We know have three paths from node 'a'.
However, these paths are not yet
guaranteed to be the shortest path. To be
sure we have the shortest path, we have
to keep going.

The next move in the algorithm is to


move to the nearest node from node 'a'.

In this case that is node 'c'.

Figure 3: Dijkstra's Algorithm

At node 'c' we have paths available to nodes 'b'


and 'h'. When calculating the distances we
have to calculate the distances from node 'a'.
In this case that means the following:

Table 4: Distance to nodes (from 'a') accesible


from node 'a'
Node Distance to Node from Node 'a'
b 6
h 13

These values are then compared to the values stored in the Table 3. It can be seen that
both of these values are less than the current values stored in the table, as such table 3
becomes:

23CS1302 31 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Table 5: Entries for distances to nodes from


Node 'a'
Node Distance to Node from Node 'a'
b 6
c 4
d 5
e INFINTE
f INFINTE
g INFINTE
h 13
i INFINTE

This step has illustrated one of the advantages of dijkstra's algorithm: the route to node 'b'
is not the most direct route, but it is the shortest route; Dijkstra's Algorithm can find the
shortest route, even when that route is
not the most direct route.

Figure 4: Dijkstra's Algorithm

Again, all paths accesible from node 'c'


have been checked, and the table of
paths has been updated. Node 'c' is
marked as visited.

IMPORTANT:

1. A Visited node is never re-


visited.
2. Once a node has been marked
visited, the path to that node is
known to be the shortest route
from the initial node.

In that case, we should add another column to our table:

Table 6: Entries for distances to nodes from


Node 'a'

23CS1302 32 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Distance to Node from Node


Node Visited
'a'
b 6 NO
c 4 YES
d 5 NO
e INFINTE NO
f INFINTE NO
g INFINTE NO
h 13 NO
i INFINTE NO

As these value are being updated, the route that accompanies these distances also needs
to be stored.

Once again, the table of paths is consulted, and the shortest path to a node that has not
been visited is found. This node becomes the next current node. In this case, that is node
'd'.

Figure 5: Dijkstra's Algorithm

From node 'd', the following paths are available:

Table 7: Distance to nodes (from 'a') accesible


from node 'a'
Node Distance to Node from Node 'a'

23CS1302 33 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

f 14

The table of all paths is updated to reflect that, and the node 'd' is marked as visited, this
locks in the shortest path to node 'd' also:

Table 8: Entries for distances to nodes from


Node 'a'
Distance to Node from Node
Node Visited
'a'
b 6 NO
c 4 YES
d 5 YES
e INFINTE NO
f 14 NO
g INFINTE NO
h 13 NO
i INFINTE NO

It can be seen from table 8 above, that the next nearest node to node 'a' is node 'b'. All
paths from node 'b' are examined next. In this instance, we have a path to a node that is
marked as visited: node 'c', we already know that the path to node 'c' is as short as it can
get (the node being marked as visited is
the marker for this).

Figure 6: Dijkstra's Algorithm

As figure 6 shows, we check the path the


only other node accesible from node 'b':
node 'e'. This updates our paht table as
follows:

23CS1302 34 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Table 9: Entries for distances to nodes from


Node 'a'
Distance to Node from Node
Node Visited
'a'
b 6 YES
c 4 YES
d 5 YES
e 31 NO
f 14 NO
g INFINTE NO
h 13 NO
i INFINTE NO

Table 9 again tells us that the next node for


us to visit is node 'h'.

Figure 7: Dijkstra's Algorithm

We add up the paths, and mark the nodes


as visited...

23CS1302 35 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

Figure 8: Dijkstra's Algorithm

We keep on doing this....

Figure 9: Dijkstra's Algorithm

Until all the nodes have been visited!

Applications of Graph:

Graphs and Graph theory find various application in many real life applications. Some of
them are listed below:

1. The link structure of a website could be represented by a directed graph: the vertices
are the web pages available at the website and a directed edge from page A to page B
exists if and only if A contains a link to B.

2. A graph structure can be extended by assigning a weight to each edge of the graph.
Graphs with weights, or weighted graphs, are used to represent structures in which pair

23CS1302 36 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

wise connections have some numerical values. For example if a graph represents a road
network, the weights could represent the length of each road. A digraph with weighted
edges in the context of graph theory is called a network.

3. Networks have many uses in the practical side of graph theory, network analysis (for
example, to model and analyze traffic networks). Within network analysis, the definition
of the term "network" varies, and may often refer to a simple graph.

Many applications of graph theory exist in the form of network analysis. These split
broadly into three categories.

i. Firstly, analysis to determine structural properties of a network, such as the distribution


of vertex degrees and the diameter of the graph. A vast number of graph measures exist,
and the production of useful ones for various domains remains an active area of research.

ii. Secondly, analysis to find a measurable quantity within the network, for example, for a
transportation network, the level of vehicular flow within any portion of it.

iii. Thirdly, analysis of dynamical properties of networks.

A directed graph may be used to represent a network of processing elements; in this


formulation, data enters a processing element through its incoming edges and leaves the
element through its outgoing edges. Examples of this include the following:

 In electronic circuit design, a combinational logic circuit is an acyclic system of


logic gates that computes a function of an input, where the input and output of the
function are represented as individual bits.
 A Bayesian network represents a system of probabilistic events as nodes in a
directed acyclic graph. The likelihood of an event may be calculated from the
likelihoods of its predecessors in the DAG. In this context, the moral graph of a
DAG is the undirected graph created by adding an (undirected) edge between all
parents of the same node (sometimes called marrying), and then replacing all
directed edges by undirected edges.

23CS1302 37 DATA STRUCTURES


PANIMALAR ENGINERRING COLLEGE II YEAR/III SEM B.E-CSE

 Dataflow programming languages describe systems of values that are related to


each other by a directed acyclic graph. When one value changes, its successors
are recalculated; each value is evaluated as a function of its predecessors in the
DAG.

23CS1302 38 DATA STRUCTURES

You might also like