0% found this document useful (0 votes)
11 views68 pages

UNIT-4

Uploaded by

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

UNIT-4

Uploaded by

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

GRAPH

Graph
Graph is a non-linear data structure. It contains a set of
points known as nodes (or vertices) and a set of links
known as edges (or Arcs). Here edges are used to
connect the vertices
Graph is a collection of nodes and edges in which nodes
are connected with 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)}.
Graph Terminology

1) Vertex
Individual data element of a graph is called as Vertex.
Vertex is also known as node.
2) Edge
• An edge is a connecting link between two vertices.
Edge is also known as Arc. An edge is represented as
(startingVertex, endingVertex).
Types of Edges
• Undirected Edge - An undirected edge is a
bidirectional edge. If there is undirected edge
between vertices A and B then edge (A , B) is equal to
edge (B , A).
• Directed Edge - A directed edge is a unidirectional
edge. If there is directed edge between vertices A
and B then edge (A , B) is not equal to edge (B , A).
• Weighted Edge - A weighted edge is a edge with
value (cost) on it.
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.
Mixed Graph
• A graph with both undirected and directed edges is
said to be mixed graph
• Self-loop
• Edge (undirected or directed) is a self-loop if its two
endpoints coincide with each other.
• Simple Graph
• A graph is said to be simple if there are no parallel
and self-loop edges.
• Path
• A path is a sequence of alternate vertices and edges
that starts at a vertex and ends at other vertex such
that each edge is incident to its predecessor and
successor vertex.
Graph Representations

• Graph data structure is represented using following


representations...
• Adjacency Matrix
• Incidence Matrix
• Adjacency List
Adjacency Matrix

• In this representation, the graph is represented using


a matrix of size total number of vertices by a total
number of vertices. That means a graph with 4
vertices is represented using a matrix of size 4X4. In
this matrix, both rows and columns represent
vertices. This matrix is filled with either 1 or 0. Here,
1 represents that there is an edge from row vertex to
column vertex and 0 represents that there is no edge
from row vertex to column vertex.
Adjacency Matrix
Directed graph representation
Incidence Matrix

• In this representation, the graph is represented using a


matrix of size total number of vertices by a total
number of edges. That means graph with 4 vertices
and 6 edges is represented using a matrix of size 4X6.
In this matrix, rows represent vertices and columns
represents edges. This matrix is filled with 0 or 1 or -1.
Here, 0 represents that the row edge is not connected
to column vertex, 1 represents that the row edge is
connected as the outgoing edge to column vertex and -
1 represents that the row edge is connected as the
incoming edge to column vertex.
Incidence Matrix
Adjacency List

• In this representation, every vertex of a graph


contains list of its adjacent vertices.
For example, consider the following directed graph
representation implemented using linked list.
Adjacency List

• This representation can also be implemented


using an array as follows
SHORTEST PATH
Dijkstra’s Algorithm

Dijkstra’s Algorithm is one of the very famous greedy


algorithms.
It is used for solving the single source shortest path
problem which gives the shortest paths from one
particular source node to all the other nodes of the
given graph.
Conditions for Dijkstra’s Algorithm-

 Dijkstra’s algorithm works only for those graphs that are


connected.
 Dijkstra’s algorithm works only for those graphs that do
not contain any edges with negative weights.
 The actual Dijkstra’s algorithm does not output the
shortest paths. It only provides the value or cost of the
shortest paths.
 By making minor modifications in the actual algorithm, the
shortest paths can be easily obtained.
 Dijkstra’s algorithm works for directed as well as
undirected graphs.
Problem

Using Dijkstra’s Algorithm, find out the shortest


distance from the source vertex ‘S’ to the rest of the
vertices in the given graph.
Also, write the order in which all the vertices of the
graph are visited.
Solution

Step-01: We will create the two sets as-


Unvisited set : {S , a , b , c , d , e} Visited set : { }
Step-02:
Now, we will create two variables Π and d for each
vertex and initialize them as-
Π[S] = Π[a] = Π[b] = Π[c] = Π[d] = Π[e] = NIL
d[S] = 0
d[a] = d[b] = d[c] = d[d] = d[e] = ∞
Solution
Now, Our SPT becomes-

Now, we update the sets as-


Unvisited set : {a , b , c , d , e}
Visited set : {S}
Solution
Now, we will choose vertex ‘a’ and relax its outgoing
edges because among unprocessed vertices, shortest
path estimate for vertex ‘a’ is least.
Now,
d[a] + 2 = 1 + 2 = 3 < ∞
∴ d[c] = 3 and Π[c] = a
d[a] + 1 = 1 + 1 = 2 < ∞
∴ d[d] = 2 and Π[d] = a
d[a] + 2 = 1 + 2 = 3 < 5
∴ d[b] = 3 and Π[b] = a
Solution
Now, Our SPT becomes-

Now, we update the sets as-


Unvisited set : {b , c , d , e}
Visited set : {S , a}
Solution
Now, we will choose vertex ‘d’ and relax its outgoing
edges because among unprocessed vertices, shortest
path estimate for vertex ‘d’ is least.
Initially-
Now,
d[d] + 2 = 2 + 2 = 4 < ∞
∴ d[e] = 4 and Π[e] = d
Solution
Now, Our SPT becomes-

Now, we update the sets as-


Unvisited set : {b , c , e}
Visited set : {S , a , d}
Solution
Now, we will choose vertex ‘b’ and relax its outgoing edges. We can
choose any of the vertices ‘b’ or ‘c’ because among unprocessed
vertices, for both of them, shortest path estimate is least.
Initially-
Now,
d[b] + 2 = 3 + 2 = 5 > 2
∴ No change
So, Our SPT remains the same .
Now, we update the sets as-
Unvisited set : {c , e}
Visited set : {S , a , d , b}
Solution
Now, we choose vertex ‘c’ and relax its outgoing edges because among
unprocessed vertices, shortest path estimate for vertex ‘c’ is least.
Initially-
Now,
d[c] + 1 = 3 + 1 = 4 = 4
d[c]+3=3+3=6>2
∴ No change
Now, Our SPT remains the same .
Now, we update the sets as-
Unvisited set : {e}
Visited set : {S , a , d , b , c}
Solution
Now, we choose vertex ‘e’ and relax its outgoing edges
because it is the only remaining unprocessed vertex.
There are no outgoing edges for vertex ‘e’. So, Our SPT
remains the same .
Now, we update the sets as-
Unvisited set : { }
Visited set : {S , a , d , b , c , e}
Solution
Now, All the vertices of the graph have been processed,
so we are done.
Thus, Our final Shortest Path Tree is as follows which
represents the shortest paths from the source vertex
‘S’ to all other vertices of the given graph-
The order in which all
the vertices have
been processed is-
S,a,d,b,c,e
Dijkstra’s Algorithm
dist[S] ← 0 // We set the distance to source vertex as 0
Π[S] ← NIL // We set the predecessor of source vertex as NIL
for all v ∈ V – {S} // For all other vertices
do dist[v] ← ∞ // We set all other distances to ∞
Π[v] ← NIL // We set the predecessor of all other vertices as NIL
S←∅ // The set of vertices that have been visited ‘S’ is initially
empty
Q←V // The queue ‘Q’ initially contains all the vertices
while Q ≠ ∅ // While loop executes till the queue is not empty
Dijkstra’s Algorithm
do u ← mindistance (Q, dist) // We select a vertex from Q with the
least distance
← S ∪ {u} // We add vertex ‘u’ to ‘S’ list of vertices that have been
visited
for all v ∈ neighbors[u] // For all the neighboring vertices of vertex ‘u’
do if dist[v] > dist[u] + w(u,v) // if any new shortest path is Discovered
then dist[v] ← dist[u] + w(u,v) // We select the new value of the
shortest path
return dist
Kruskal's Algorithm
 Kruskal's algorithm to find the minimum cost
spanning tree uses the greedy approach.
 This algorithm treats the graph as a forest and every
node it has as an individual tree.
 A tree connects to another only and only if, it has
the least cost among all available options and does
not violate MST properties.
Kruskal's Algorithm Example
Kruskal's Algorithm Example
Step 1 - Remove all self loops and Parallel Edges
 Remove all loops and parallel edges from the given
graph.
 In case of parallel edges, keep the one which has the
least cost associated and remove all others.
Kruskal's Algorithm Example
Step 2 - Arrange all edges in their increasing order of
weight
The next step is to create a set of edges and weight,
and arrange them in an ascending order of weightage
(cost).
Kruskal's Algorithm Example
Step 3 - Add the edge which has the least weightage
• Now we start adding edges to the graph beginning
from the one which has
• The least cost is 2 and edges involved are B,D and D,T.
We add them.
Kruskal's Algorithm Example
• Next cost is 3, and associated edges are A,C and C,D.
We add them again −
Kruskal's Algorithm Example
• Next cost in the table is 4, and we observe that
adding it will create a circuit in the graph. −

• We ignore it. In the process we shall ignore/avoid all


edges that create a circuit
Kruskal's Algorithm Example

• We observe that edges with cost 5 and 6 also create


circuits. We ignore them and move on.
Kruskal's Algorithm Example
• Now we are left with only one node to be added.
Between the two least cost edges available 7 and 8,
we shall add the edge with cost 7.
Kruskal's Algorithm Example
• Total cost = 7+3+3+2+2=17
PRIMS Algorithm Example
• Construct the minimum spanning tree (MST) for the
given graph using Prim’s Algorithm-
PRIMS Algorithm Example
VERTEX EDGE WEIGHT
2 (1,2) 28
6 (1,6) 10
PRIMS Algorithm Example
VERTEX EDGE WEIGHT
2 (1,2) 28
5 (6,5) 25
PRIMS Algorithm Example
VERTEX EDGE WEIGHT
2 (1,2) 28

4 (5,4) 22
7 (5,7) 24
PRIMS Algorithm Example
VERTEX EDGE WEIGHT
2 (1,2) 28

7 (5,7),(4,7) 24,18
3 (4,3) 12
PRIMS Algorithm Example
VERTEX EDGE WEIGHT
2 (1,2), (3,2) 28,16

7 (5,7),(4,7) 24,18
PRIMS Algorithm Example
VERTEX EDGE WEIGHT
7 (5,7),(4,7),(2,7) 24,18,14
PRIMS Algorithm Example
Since all the vertices have been included in the MST, so
we stop.
Weight of the MST
= Sum of all edge weights
= 10 + 25 + 22 + 12 + 16 + 14
= 99 units
PRIMS Algorithm Example-2
Construct the minimum spanning tree (MST) for the
given graph using Prim’s Algorithm-
PRIMS Algorithm Example-2
• Solution:-
PRIMS Algorithm Example-2
Solution:-
Weight of the MST
= Sum of all edge weights
= 1 + 4 + 2 + 6 + 3 + 10
= 26 units
Graph Traversal
Graph traversal is a technique used for a searching
vertex in a graph.
The graph traversal is also used to decide the order of
vertices is visited in the search process.
A graph traversal finds the edges to be used in the
search process without creating loops. That means
using graph traversal we visit all the vertices of the
graph without getting into looping path.
Graph traversal techniques
• DFS (Depth First Search)
• 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 loops.
• We use Stack data structure with maximum size of
total number of vertices in the graph to implement
DFS traversal.
BFS (Breadth First Search)

• BFS traversal of a graph produces a spanning tree as


final result.
• Spanning Tree is a graph without loops.
• We use Queue data structure with maximum size of
total number of vertices in the graph to implement
BFS traversal.
Differences between BFS and DFS
BFS DFS
Full form BFS stands for Breadth DFS stands for Depth First
First Search. Search.
Technique It a vertex-based It is an edge-based
technique to find the technique because the
shortest path in a graph. vertices along the edge are
explored first from the
starting to the end node.
Definition BFS is a traversal DFS is also a traversal
technique in which all the technique in which traversal
nodes of the same level is started from the root node
are explored first, and and explore the nodes as far
then we move to the next as possible until we reach
level. the node that has no
unvisited adjacent nodes.
Data Queue data structure is Stack data structure is used
Structure used for the BFS traversal. for the BFS traversal.
Differences between BFS and DFS
BFS DFS
Backtracki BFS does not use the DFS uses backtracking to
ng backtracking concept. traverse all the unvisited
nodes.
Number of BFS finds the shortest In DFS, a greater number of
edges path having a minimum edges are required to
number of edges to traverse from the source
traverse from the source vertex to the destination
to the destination vertex. vertex.

Optimality BFS traversal is optimal DFS traversal is optimal for


for those vertices which those graphs in which
are to be searched closer solutions are away from the
to the source vertex. source vertex.

Speed BFS is slower than DFS. DFS is faster than BFS.


Memory It is not memory efficient It is memory efficient as it
efficient as it requires more requires less memory than
memory than DFS. BFS.

You might also like