Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
56 views64 pages

Data Structures and Algorithms (BCO 002A) UNIT-5

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 64

DATA STRUCTURES AND ALGORITHMS

(BCO 002A)

UNIT-5
GRAPH

• It is basically a collection of vertices (also called nodes)


and edges that connect these vertices.
• A graph is often viewed as a generalization of the tree
structure, where instead of having a purely parent-to-child
relationship between tree nodes, any kind of complex
relationship can exist.
WHY ARE GRAPHS USEFUL?

• Graphs are widely used to model any situation where


entities or things are related to each other in pairs.
• For example, the following information can be represented
by graphs:
 Family trees in which the member nodes have an edge
from parent to each of their children.
 Transportation networks in which nodes are airports,
intersections, ports, etc. The edges can be airline flight
routes, one-way roads, shipping routes, etc.
DEFINITION

• A graph G is defined as an ordered set (V, E), where V(G)


represents the set of vertices and E(G) represents the
edges that connect these vertices.
• Figure shows a graph with V(G) = {A, B, C, D and E} and
E(G) = {(A, B), (B, C), (A, D), (B, D), (D, E), (C, E)}.
• Note that there are five vertices or nodes and six edges in
the graph.
TERMINOLOGY OF GRAPH

• Undirected Graph: A Graph can be directed or


undirected. In an undirected graph, edges do not have any
direction associated with them. That is, if there is an edge
between vertex A and B then the vertices can be traversed
A to B, as well as B to A.
• Directed Graph: A directed graph or digraph is a graph,
where the vertices are connected together and all the
edges are directed from one vertex to another.
TERMINOLOGY OF GRAPH

• Adjacent vertices or neighbors: For every edge e=(u, v),


that connects vertices u and v, the vertices u and v are
endpoints and are said to be the adjacent vertices or
neighbors.
• Degree: The degree of a vertex of a graph is the number
of edges incident to the vertex, with self-loops counted
twice. The degree of a vertex v is denoted by deg (v) or
deg v.
TERMINOLOGY OF GRAPH

• Regular graph: It is a graph, where each vertex has same


no of neighbors. That is, every vertex has the same
degree.
TERMINOLOGY OF GRAPH

• Walk: A walk of a graph is a finite altering sequence of


vertices and edges beginning and ending with vertices. In
a walk, no edge is traversed more than one.
• Open Walk: An open walk is that where no edge is
repeated. V1-e1-V2-e5-V5-e7-V3-e3-V4 in the following
graph G is an open walk as no edge is repeated.
• Closed Walk: A walk having same starting and end point
is called closed walk. V1-e1-V2-e2-V4-e11-V3-e4-V1 is a
closed walk where both starting and end vertex is V1.
TERMINOLOGY OF GRAPH
TERMINOLOGY OF GRAPH

• Path: A path P is written as P = {v0, v1, v2...vn}, of length n


from a vertex u to v is defined as a sequence of (n+1)
vertices. Here, u = v0, v = vn, and vi-1 is adjacent to vi for i
= 1, 2, 3… n.
• Closed Path: A path is known as a closed path if the edge
has same endpoints. In previous figure V1-V2-V4-V3-V1 is
a closed path with same end point V1.
• Cycle: A path in which the first and last vertices are same
and no repeated edges or vertices.
TERMINOLOGY OF GRAPH

• Cycle: A path in which the first and last vertices are same
and no repeated edges or vertices.
• A graph is said to be acyclic if it contains no cycles.
• A directed graph that is acyclic is called Directed Acyclic
Graph (DAG).
• Connected Graph: A graph is called connected graph, if
and only if there is a simple path between any two vertices
of a graph. A connected graph without any cycle is a tree.
TERMINOLOGY OF GRAPH

(a) connected undirected graph, (b) connected directed graph


TERMINOLOGY OF GRAPH

• Complete Graph: A complete graph is a simple graph in


which every node is adjacent to every other node. A
complete graph with n number of vertices has n(n-1)/2
edges.
TERMINOLOGY OF GRAPH

• Weighted graph: A weighted graph is the one in which we


associate some weight with every edge.
TERMINOLOGY OF GRAPH

• Subgraph: A subgraph H of a graph G, is a graph whose


vertices are a subset of the vertex set of G and whose
edges are a subset of the edge set of G.
TERMINOLOGY OF
DIRECTED GRAPH

• Out-degree of a node: The out degree of a node u,


written as outdeg(u), is the number of edges that
originate at u.
• In-degree of a node: The in degree of a node u, written
as indeg(u), is the number of edges that terminate at u.
• Degree of a node: Degree of a node written as deg(u) is
equal to the sum of in-degree and out-degree of that
node. Therefore, deg(u) = indeg(u) + outdeg(u)
TERMINOLOGY OF
DIRECTED GRAPH

• Source: A node u is known as a source if it has a positive


out-degree but an in-degree= 0.
• Sink: A node u is known as a sink if it has a positive in-
degree but a zero out-degree.
• Reachability: A node v is said to be reachable from node
u, if and only if there exists a (directed) path from node u
to node v.
TERMINOLOGY OF
DIRECTED GRAPH

• Strongly connected directed graph: A digraph is said to


be strongly connected if and only if there exists a path
from every pair of nodes in G. That is, if there is a path
from node u to v, then there must be a path from node v
to u.
• Parallel/Multiple edges: Distinct edges which connect
the same end points are called multiple edges.
That is, e = {u, v) and e’ = (u, v) are known as multiple
edges of G.
GRAPHS REPRESENTATION IN
DATA STRUCTURE

1. Adjacency matrix representation


• In adjacency matrix representation, we have a matrix of order
n*n where n is the number of nodes in the graph. The matrix
represents the mapping between various edges and vertices.
• In the matrix, each row and column represents a vertex. The
values determine the presence of edges.
• Let Aij represents each element of the adjacency matrix. Then,
for an undirected graph, the value of Aij is 1 if there exists an
edge between i and j. Otherwise, the value of Aij is 0.
GRAPHS REPRESENTATION IN
DATA STRUCTURE
GRAPHS REPRESENTATION IN
DATA STRUCTURE

2. Adjacency list representation


• The adjacency list is an array of linked lists where the array
denotes the total vertices and each linked list denotes the
vertices connected to a particular node.
• In a linked list, the most important component is the pointer
named ‘Head’ because this single pointer maintains the whole
linked list. For linked list representation, we will have total
pointers equal to the number of nodes in the graph.
GRAPHS REPRESENTATION IN
DATA STRUCTURE
GRAPHS REPRESENTATION IN
DATA STRUCTURE
GRAPH TRAVERSAL ALGORITHMS

• By traversing a graph, we mean the method of examining


the nodes and edges of the graph.
• There are two standard methods of graph traversal-
1. Breadth First Search
2. Depth First Search
GRAPH TRAVERSAL ALGORITHMS

• Both start at some vertex v and then visit all vertices


reachable from v (that is, all vertices w such that there is a
path from v to w).
• If there are vertices that remain unvisited, that is, if there
are vertices that are not reachable from v, then BFS and
DFS pick a new vertex v0 and visit all vertices reachable

from v0.
• They repeat this process until they have finally visited all
vertices.
GRAPH TRAVERSAL ALGORITHMS

• While breadth first search will use a queue as an auxiliary


data structure to store nodes for further processing, the
depth-first search scheme will use a stack.
• But both these algorithms will make use of a variable
STATUS.
• During the execution of the algorithm, every node in the
graph will have the variable STATUS set to 1, 2 or 3,
depending on its current state. Table I shows the value of
status and its significance:
GRAPH TRAVERSAL ALGORITHMS

STATUS STATE OF DESCRIPTION


THE NODE

1 Ready The initial state of the node N

Node N is placed on the queue or stack


2 Waiting
and waiting to be processed

3 Processed Node N has been completely processed


BREADTH FIRST SEARCH
ALGORITHM
• Breadth-first search (BFS) is a graph search algorithm that
begins at the root node and explores all the neighboring
nodes.
• Then for each of those nearest nodes, the algorithm
explores their unexplored neighbor nodes, and so on, until
it finds the goal.
• That is, we start examining the node A and then all the
neighbors of A are examined.
• In the next step we examine the neighbors of neighbors of
A, so on and so forth.
BREADTH FIRST SEARCH
ALGORITHM
Algorithm for breadth-first search in a graph G beginning
at a starting node A
Step 1: SET STATUS = 1 (ready state) for each node in G.
Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until QUEUE is empty
Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed
state).
Step 5: Enqueue all the neighbors of N that are in the ready state (with
STATUS = 1) and set their STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT
BREADTH FIRST SEARCH
ALGORITHM

Example:
Consider the graph G given on next slide.
The adjacency list of G is also given.
Assume that G represents the daily flights between different
cities and we want to fly from city A to H with minimum stops.
That is, find the minimum path P from A to H given that every
edge has length = 1.
BREADTH FIRST SEARCH
ALGORITHM

Adjacency Lists
A: B, C, D
B: E
C: B, G
D: C, G
E: C, F
F: C, H
G: F, H, I
H: E, I
I: F
BREADTH FIRST SEARCH
ALGORITHM

a) Initially add A to QUEUE and add NULL to ORIG, so


FRONT = 1 QUEUE = A
REAR = 1 ORIG = \0

b) Dequeue a node by setting FRONT = FRONT + 1 (remove the


FRONT element of QUEUE) and enqueue the neighbors of A. Also add
A as the ORIG of its neighbors, so
FRONT = 2 QUEUE = A B C D
REAR = 4 ORIG = \0 A A A
BREADTH FIRST SEARCH
ALGORITHM

c) Dequeue a node by setting FRONT = FRONT + 1 and enqueue the


neighbors of B. Also add B as the ORIG of its neighbors, so
FRONT = 3 QUEUE = A B C D E
REAR = 5 ORIG = \0 A A A B
BREADTH FIRST SEARCH
ALGORITHM

d) Dequeue a node by setting FRONT = FRONT + 1 and enqueue the


neighbors of C. Also add C as the ORIG of its neighbors. Note that C
has two neighbors B and G. Since B has already been added to the
queue and it is not in the Ready state, we will not add B and add only
G, so
FRONT = 4 QUEUE = A B C D E G
REAR = 6 ORIG = \0 A A A B C
BREADTH FIRST SEARCH
ALGORITHM

e) Dequeue a node by setting FRONT = FRONT + 1 and enqueue the


neighbors of D. Also add D as the ORIG of its neighbors. Note that D
has two neighbors C and G. Since both of them have already been
added to the queue and they are not in the Ready state, we will not
add them again, so
FRONT = 5 QUEUE = A B C D E G
REAR = 6 ORIG = \0 A A A B C
BREADTH FIRST SEARCH
ALGORITHM

f) Dequeue a node by setting FRONT = FRONT + 1 and enqueue the


neighbors of E. Also add E as the ORIG of its neighbors. Note that E
has two neighbors C and F. Since C has already been added to the
queue and it is not in the Ready state, we will not add C and add only
F, so
FRONT = 6 QUEUE = A B C D E G F
REAR = 7 ORIG = \0 A A A B C G
BREADTH FIRST SEARCH
ALGORITHM

g) Dequeue a node by setting FRONT = FRONT + 1 and enqueue the


neighbors of G. Also add G as the ORIG of its neighbors. Note that G
has three neighbors F, H and I.
FRONT = 7 QUEUE = A B C D E G F H I
REAR = 10 ORIG = \0 A A A B C G G G
BREADTH FIRST SEARCH
ALGORITHM

h) Since I is our final destination, we stop the execution of this


algorithm as soon as it is encountered and added to the QUEUE.
Now backtrack from I using ORIG to find the minimum path P.
Thus, we have P as A -> C -> G -> I.
DEPTH FIRST SEARCH
ALGORITHM
• The Depth-First Search algorithm begins at a starting node
A which becomes the current node.
• Then it examines each node N along a path P which
begins at A. That is, we process a neighbor of A, then a
neighbor of neighbor of A and so on.
• During the execution of the algorithm, if we reach a path
that has a node N that has already been processed, then
we backtrack to the current node. Otherwise, the un-
visited (un-processed node) becomes the current node.
DEPTH FIRST SEARCH
ALGORITHM
Algorithm for depth-first search in a graph G beginning at
a starting node A
Step 1: SET STATUS = 1 (ready state) for each node in G.
Step 2: Push the starting node A on the stack and set its STATUS = 2
(waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed
state).
Step 5: Push on to the stack all the neighbors of N that are in the ready
state (with STATUS = 1) and set their STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT
DEPTH FIRST SEARCH
ALGORITHM

Example:
Consider the graph G given on next slide.
The adjacency list of G is also given.
Suppose we want to print all nodes that can be reached from the
node H (including H itself).
One alternative is to use a Depth- First Search of G starting at node H.
DEPTH FIRST SEARCH
ALGORITHM

Adjacency Lists
A: B, C, D
B: E
C: B, G
D: C, G
E: C, F
F: C, H
G: F, H, I
H: E, I
I: F
DEPTH FIRST SEARCH
ALGORITHM

a) Push H on to the stack


STACK: H

b) Pop and Print the top element of the STACK, that is, H. Push all the
neighbors of H on to the stack that are in the ready state. The STACK
now becomes:
STACK: E, I
DEPTH FIRST SEARCH
ALGORITHM

c) Pop and Print the top element of the STACK, that is, I. Push all the
neighbors of I on to the stack that are in the ready state. The STACK
now becomes:
PRINT: I STACK: E, F
d) Pop and Print the top element of the STACK, that is, F. Push all the
neighbors of F on to the stack that are in the ready state. (Note F has
two neighbors C and H. but only C will be added as H is not in the
ready state). The STACK now becomes:
PRINT: F STACK: E, C
DEPTH FIRST SEARCH
ALGORITHM

e) Pop and Print the top element of the STACK, that is, C. Push all the
neighbors of C on to the stack that are in the ready state. The STACK
now becomes:
PRINT: C STACK: E, B, G
f) Pop and Print the top element of the STACK, that is, G. Push all the
neighbors of G on to the stack that are in the ready state. Since there
are no neighbors of G that are in the ready state no push operation is
performed. The STACK now becomes:
PRINT: G STACK: E, B
DEPTH FIRST SEARCH
ALGORITHM
g) Pop and Print the top element of the STACK, that is, B. Push all the
neighbors of B on to the stack that are in the ready state. Since there
are no neighbors of B that are in the ready state no Push operation is
performed. The STACK now becomes:
PRINT: B STACK: E
h) Pop and Print the top element of the STACK, that is, E. Push all the
neighbors of E on to the stack that are in the ready state. Since there
are no neighbors of E that are in the ready state no Push operation is
performed.
PRINT: E STACK: NULL
DEPTH FIRST SEARCH
ALGORITHM
i) Since the STACK is now empty, the depth-first search of G starting
at node H is complete and the nodes which were printed are- H,
I, F, C, G, B E.
SPANNING TREE

• A spanning tree of a connected, undirected graph G, is a sub-graph


of G which is a tree that connects all the vertices together. A graph
G can have many different spanning trees.
MINIMUM SPANNING TREE

• When we assign weights to each edge and use it to assign a


weight to a spanning tree by calculating the sum of the weights of
the edges in that spanning tree.
• A minimum spanning tree (MST) is defined as a spanning tree
with weight less than or equal to the weight of every other
spanning tree. In other words, a minimum spanning tree is a
spanning tree that has weights associated with its edges, and the
total weight of the tree (the sum of the weights of its edges) is at a
minimum.
KRUSKAL'S ALGORITHM

• Let G = (V, E) be a graph with |v| = n.

• T is the set of minimum cost edges which is initially empty or null.

• N is the number of vertices of a graph G.

• Assume v and w be any two adjacent vertexes of G.


KRUSKAL'S ALGORITHM
KRUSKAL'S ALGORITHM
KRUSKAL'S ALGORITHM
PRIM’S ALGORITHM

• Suppose V = {v1, v2, v3, v4…vn} of a weighted undirected graph G


= (V, E).
• The Prim‘s algorithm begins with a set V’, such that V‟ = {u}.
• It then grows a spanning tree one edge at a time.
• At each step it finds the shortest edge (u, v) that connects W and
(V−V‟) and then adds v, the vertex in (V−V’) to V’.
• It repeats this step until V’= V.
• E is the set of edges, which are to be extracted to obtain the
minimum cost spanning tree.
PRIM’S ALGORITHM
PRIM’S ALGORITHM
PRIM’S ALGORITHM
SHORTEST PATHS

• Shortest path problem states a way to find the path in a weighted


graph connecting two given vertices u and v with the property
that the sum of the weights of all the edges is minimized over all
such paths.
• There are a few variants of the shortest path problem:
1. Single-source shortest-path problem
2. Single-destination shortest paths problem
3. Single-pair shortest-path problem
4. All-pairs shortest paths problem
DIJKSTRA’S ALGORITHM

• This algorithm finds the shortest path to a vertex to the rest of the
vertices in a graph.
• First, it explores the shortest path from the source to a vertex nearest to
it, then to a second nearest, and so on.
• The one constraint for this algorithm is that all the edges must be non-
negative edges. Following are given:
 G = (V, E) is a weighted connected graph,
 W = weight matrix
 S = set of visited vertices from source vertex to destination vertex,
initially it is empty.
 s = source vertex, dist[v] = distance of vertex v from s
DIJKSTRA’S ALGORITHM

• Dijkstra's algorithm keeps two sets of vertices:


 S: the set of vertices whose shortest paths from the source have already
been determined and
 V-S: the remaining vertices.

• The other data structures needed are:


 d: array of best estimates of shortest path to each vertex
 pi: an array of predecessors for each vertex
DIJKSTRA’S ALGORITHM

Algorithm:
1. Initialise d and pi,
2. Set S to empty,
3. While there are still vertices in V-S:
a. Sort the vertices in V-S according to the current best
estimate of their distance from the source,
b. Add u, the closest vertex in V-S, to S,
c. Relax all the vertices still in V-S connected to u.
DIJKSTRA’S ALGORITHM
DIJKSTRA’S ALGORITHM
DIJKSTRA’S ALGORITHM

You might also like