Graph 1

International Islamic University
International Islamic UniversityVisiting Faculty Membor at International Islamic University en International Islamic University
Sunawar Khan
Islamia University of Bahawalpur
Bahawalnagar Campus
Analysis o f Algorithm
‫خان‬ ‫سنور‬ Algorithm Analysis
DFS and BFS
Graph Traversal
Representation of Graph
Minimum Spanning Tree
Topological Sort
Contents
‫خان‬ ‫سنور‬ Algorithm Analysis
Topics
• Graph Terminology
• Graph Representation
• Matrix Representation
• Linked List Representation
• Depth First Search Algorithm(DFS)
• Strategy
• Application
• Analysis
• Breadth First Search Algorithm(BFS)
• Strategy
• Application
• Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
What is Graph
• A graph G = (V, E) is a set of vertices V and a set of edges E, where
• E ⊆ V x V(Subset of cross-product of vertices called binary relation)
• Example: Let G = (V, E) where
• V = {a, b, c, d}
• E = {(a, b) , (a, d) , (b, c) , (b, a) , (c, d) , (b, d) , (d, d)}
• The number of vertices and edges are given by the cardinalities |V| and |E| of
the corresponding sets. The sample graph consists of four vertices and seven
edges. Thus,
|V| = 4, |E| = 7
• Graph are usually represented by pictorial diagrams. The vertices can be shown
as labeled CIRCLE or RECTANGLES. The edges are depicts arcs lines. Except for
some applications, in which distances among vertices are important, the
positions of the vertices are in general, immaterial. Thus, graphs can be shown
pictorially in several ways.
‫خان‬ ‫سنور‬ Algorithm Analysis
Basic Terminologies
• Mathematical graphs can be represented in data structure. We can
represent a graph using an array of vertices and a two-dimensional array
of edges. Before we proceed further, let's familiarize ourselves with some
important terms −
• Vertex
• Edges
• Adjacency
• Path
‫خان‬ ‫سنور‬ Algorithm Analysis
Vertex
• Each node of the graph is represented as a vertex. In the following
example, the labeled circle represents vertices. Thus, A to G are vertices.
We can represent them using an array as shown in the following image.
Here A can be identified by index 0. B can be identified using index 1 and
so on.
‫خان‬ ‫سنور‬ Algorithm Analysis
Edges
• Edge represents a path between two vertices or a line between two
vertices. In the following example, the lines from A to B, B to C, and so on
represents edges. We can use a two-dimensional array to represent an
array as shown in the following image. Here AB can be represented as 1 at
row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping other
combinations as 0.
‫خان‬ ‫سنور‬ Algorithm Analysis
Adjacency
• Two node or vertices are adjacent if they are connected to each other
through an edge. In the following example, B is adjacent to A, C is adjacent
to B, and so on.
‫خان‬ ‫سنور‬ Algorithm Analysis
Path
• Path represents a sequence of edges between the two vertices. In the
following example, ABCD represents a path from A to D.
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph – Undirected Graph
• A graph G = (V,E) with vertex set V = {v1,
v2, v3, . . . , vn} is called undirected if (vi, vj)
= (vj,vi) for i ≠ j
• An undirected graph is sometimes referred
to as undigraph.
• Inn pictorial representation of undirected
graph, the edges are not assigned any
direction.
• Example:- Figure shows an undirected
graph.
• G=(V. E)
• V ={a, b, c, d, e, f}
• E = {(a, b) , (a, d) , (a, f) , (b, c) , (b, e) , (c, f) ,
(c, d) , (d, e) , (e, f)}
‫خان‬ ‫سنور‬ Algorithm Analysis
Undirected Graph – Complete
• A graph which has links among all of the
vertices in a graph is referred t as
complete.
• Example: The figure shows complete
graph
• An undirected complete graph, with n
vertices, has n(n-1)/2 edges. The spaces
complexity graph is O(n2).
• A complete graph is dense. By contrast, a
graph with space complexity O(n log n) is
called sparse
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph – Directed Graph
• A graph G = (V,E) with vertex set V = {v1,
v2, v3, . . . , vn} is called undirected if (vi,
vj) = (vj,vi) for i ≠ j
• In other words, the edges (vi, vj) and (vj,
vi), associated with any pair of verties vi,
vj are considered distinct. In pictorial
representation show here wit arrows.
• The directed graph is often referred to
digraph or network.
‫خان‬ ‫سنور‬ Algorithm Analysis
Directed Graph - Complete
• A complete directed graph has links
among all of the vertices.
• Example:- The figure shows a directed
complete graph.
• A complete directed graph with n
vertices has n(n-1) edges.
‫خان‬ ‫سنور‬ Algorithm Analysis
Weighted Graphs- Undirected
• A graph in which labels or values w1,
w2, w3, . . . are associated with edges
is called weighted graph. Weights are
typically costs or distances in different
application of graphs.
• Example:- The figure shows an
example of weighted undirected
graph.
‫خان‬ ‫سنور‬ Algorithm Analysis
Weighted Graph- Directed
• A weighted graph can also be directed.
The weights attached to the edges to
the edges between the same pair of
vertices may, in general, be different
• Example :- The figure below shows an
example of the directed weighted
graph. Note that weight of edged from
vertex a to vertex b is 73 and that from
vertex b too vertex a is 35.
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Paths
• A path is a sequence of andjacent
vertices. Two vertices are called
adjacent if they are link oor
connecting edge. The path is denoted
by enclosing the vertices is a pair of
square brackets. In path, the vertices
may repeated.
• Example: The figure below depicts a
path P = [a, b, g, d, e, i, h ]in a sample
graph. The path is shown in bold red
lines.
• The number of edges connecting the vertices in a path is called
path length. The path length in the above example is 6.
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Path – Simple Path
• A path is called simple if no vertices are repeated; otherwise, the path is
referred to as non-simple.
• Example: The figures below show simple and non-simple paths in a graph.
The path P1=[ a, c, g, d, f ] is simple. The path P2=[a, c, g, d, f, c, b, f ] is
non-simple, because it passes through vertices c, f twice.
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Path - Loops
• A loop is special path that originates and
terminates at a single node, and does not
pass through other vertices.
• Example: The figure depicts two loops in a
graph, at vertices a and c
• The loops are important in certain some
applications. For example, loops represent
certain states in Finite State Automat
‫خان‬ ‫سنور‬ Algorithm Analysis
Cyclic and Acyclic Graph
• A path that originates and terminates at the same vertex, and links two or
more vertices, is called cycle. If a graph contains a cycle it is called cyclic.
By contrast, a graph which contains no cycles is known as acyclic.
• Example: In diagram (i), the path P=[b, c, d, b] is a cycle. The diagram (ii)
represents a acyclic graph.
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Representation – Adjacency Matrix
• One of the standard ways of representing a graph uses a matrix to denote links
between pairs of vertices in a graph. The matrix is known as adjacency matrix.
• The adjacency matrix can be defined mathematically. Let G=(V,E) be a graph,
with V={v1,v2,……vn}, and E={(v1,v2),(v1,v3)….}where n=|V|. The adjacency
matrix A=[aij] as
• 𝑎𝑖𝑗 = ቊ
1 𝑖𝑓 𝑣𝑡, 𝑣𝑗 ∈ 𝐸
0 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
• The definition implies that entry in the ith row and jth column of the matrix is 1
• if a link exists between the ith and jth vertex; otherwise, it is 0.
• The size adjacency matrix is with vertex set V is |V|x|V| . Thus space
complexity is θ(|V|2)
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Representation – Adjacency Matrix
• Example : Figure (i) shows a sample directed graph. Figure (ii) shows the
adjacency matrix for the graph.
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Representation- Adjacency Link List
• A graph can also be represented using linked lists. The list representation
consists of an array of linked lists, each corresponding to one vertex. The
list stores all of the vertices that are linked to a given vertex.
• Let G=(V,E) be a graph, and Adj(u) be the linked list corresponding to
vertex u, then for all v,
v ∈Adj(u), if (u ,v ) ∈E.
• The vertices belonging to Adj(u) are called neighbors of vertex u, or
adjacent vertices.
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Representation – Linked List
• Example:- The diagram below show a sample
graph and its linked list representation.
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Traversal
• In graph traversal, all vertices are visited once. Depending on the
application, the data and keys are accessed and processed further. For
example, the traversal procedure can be used to list keys stored in the
vertices The two important procedures for graph traversal are:
1) Depth First Search (DFS)
2) Breadth First Search (BFS)
• The DFS and algorithms can be used to traverse both directed and
undirected graphs
‫خان‬ ‫سنور‬ Algorithm Analysis
Depth First Search
• The Depth First Search (DFS) systematically visits all vertices of a graph.
Initially, a start vertex is chosen, and its neighbors are explored. Then
neighbors and of neighbors are explored. This process is continued till the
remotest neighbor of the start vertex is reached, which is called the dead
end. The algorithm then backtracks to the start vertex and on the way
back lists all of the vertices in depth first search order. The depth first
search algorithm belongs to the class of backtracking algorithms.
• A stack is used to implement the DFS procedure. The stack keeps track of
vertices traversed . For this purpose , the three states of vertices are
designated as ready, wait and processed, defined as follows :
• All vertices are initially in the ready state
• A vertex pushed on to the stack, is in the wait state
• A vertex popped off the stack is in the processed state
‫خان‬ ‫سنور‬ Algorithm Analysis
Algorithm
• The Depth First Search (DFS) for a connected graph consists of the
following steps:
• Step #1: Initialize all vertices to mark as unvisited (ready state)
• Step #2: Select an arbitrary vertex, push it to stack (wait state)
• Step #3: Repeat steps # 4 through Step #5 until the stack is empty
• Step #4: Pop off an element from the stack. Process and mark it as visited
(processed)
• Step #5: Push to stack adjacent vertices of the processed vertex. Go toStep
# 3.
• The same procedure is applied to a subgraph, which may contain any
unvisited vertices.
‫خان‬ ‫سنور‬ Algorithm Analysis
DFS – Spanning Tree
• Apart from extracting information stored in vertices, the DFS can be used
to construct special tree called DFS Spanning trees The Spanning trees are
useful in investigating important properties of the graphs and subgraphs
• During the DFS, a spanning tree is constructed by linking together a vertex
that is visited for the first time to the vertex from which it is reached. The
links are called
‫خان‬ ‫سنور‬ Algorithm Analysis
Example
• Consider the sample
directed graph shown
below. The steps involved in
Depth First Search are
depicted in the next set of
diagrams As the algorithm
proceeds, the depth first
spanning tree is also
generated.
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
‫خان‬ ‫سنور‬ Algorithm Analysis
Applications
• Some important applications of DFS are
(i) Checking connectivity of a graph
(ii) Checking accessibility of vertices from a given vertex
(iii) Checking cyclicity/ acyclicity of a graph
• Graph connectivity and cyclicity are illustrated by the following examples
‫خان‬ ‫سنور‬ Algorithm Analysis
Graph Connectivity
• An undirected graph is not connected if the DFS algorithm terminates
before all of the vertices have been visited. The unvisited vertices form one
or more subgraphs
• Example: Figure (i) shows a sample graph. Figure (ii) provides a DFS tree.
The vertices M.P,R,Q,D remain unvisited and constitute a disconnected
subgraph.
‫خان‬ ‫سنور‬ Algorithm Analysis
Subgraph Accessibility
• In a directed graph, all the vertices may have links, but may not be
accessible from given vertex. The inaccessible vertices can be explored by
using DFS
• Example: Figure (i) shows a sample directed graph. Figure (ii) provides a
DFS tree. The vertices L,G,A remain unvisited and constitute subgraph
whose vertices are not accessible from initial vertex M
‫خان‬ ‫سنور‬ Algorithm Analysis
Acyclic Graph
• An undirected graph is acyclic ( has no cycles) if the DFS spanning has no
back edges
• Example: Figure (i) shows a sample graph . Figure (ii) contains a DFS
Spanning Tree, which has no back edges. The graph is therefore acyclic
‫خان‬ ‫سنور‬ Algorithm Analysis
Cyclic Graph
• An undirected graph is cyclic if the DFS spanning has back edges
• Example: Figure (i) shows a sample graph . Figure (ii) contains the DFS
spanning tree, which has back edges shown in blue color. The graph is
therefore cyclic
‫خان‬ ‫سنور‬ Algorithm Analysis
Implementation
• The DFS implements depth-first-search procedure by using a stack S. The
address s of first selected vertex is passed to the method. The
implementation uses an array state[] which stores status of vertices as
READY, WAIT, PROCESSED. The graph is represented by adjacency list Adj .
The notation Adj[u] denotes a neighbor of vertex u
‫خان‬ ‫سنور‬ Algorithm Analysis
Algorithm
DFS(G, s) ► s is address of starting vertex
1. for each vertex u ∈ V[G] –{ s } ►V[G] is vertex set of graph G. V[G]-{s} is the
difference set that excludes initial vertex s.
2. do state[u] ← READY ►All unvisited vertices are assigned READY status
3. state[s] ← WAIT ► Vertex s is pushed to stack and assigned WAIT status
4. P ←φ ► Stack P is initialized as empty
5. PUSH(S,s) ► The starting vertex s is added to the stack
6. while S ≠φ. ►A loop is created to pop off vertices .
7. do u←POP(S) ► u is the popped vertex
8. for each v ∈ Adj[u] ►All vertices v that are adjacent to vertex u are explored
9. do if state[v] = READY ►If the neighbor vertex v is not visited
10. then state[v]← WAIT ►Then it is assigned WAIT state
11. PUSH(S,v) Pushed on to the stack S
12. state[u] ←PROCESSED ►The vertex u popped off the stack is marked visited
and assigned PROCESSED state
‫خان‬ ‫سنور‬ Algorithm Analysis
Analysis of DFS – Running Time
• The running time for DFS consists of following major components
Ti = Initializing vertices T
Ts = Scanning Adjacency list
• The Graph G(V,E) has |V| vertices and |E| edges. Each vertex is initialized once.
• Therefore,
Ti= |V|
• The scanning of Adjacency list takes place for each vertex. The total time is
• proportional to the number of edges scanned. Since |E| is the number of edges
in G, in
• worst case the algorithm explores all edges , therefore,
Ts = |E|
• Thus, worst case running time is given by time
TDFS= |V|+ |E|= O(|V|+|E|)
‫خان‬ ‫سنور‬ Algorithm Analysis
Breadth First Strategy - Strategy
• The Breadth First Search(BFS) is one of the standard graph traversal methods.
Each node is visited once only. The method proceeds by visiting all immediate
neighbors ( vertices one edge away), then visiting neighbor’s neighbors
(vertices two edges away), and so forth, until all reachable vertices have been
visited.
• If a graph has any subgraph(which is not reachable from the initial vertex), the
procedure may be re-started by choosing a vertex from the unvisited subgraph.
• A queue is used to implement the BFS procedure. It keeps track of vertices to
be visited next. A vertex pushed to the queue is said to be in ready state.
• An enqueued vertex is said be in wait state. The dequeued vertex is referred to
as
• .
• The queue is initialized with the address of a starting vertex.
‫خان‬ ‫سنور‬ Algorithm Analysis
Algorithm
The Breadth First Search (BFS) for a connected graph consists of following
steps:
Step #1: Initialize all vertices to mark as unvisited (ready state)
Step #2: Select an arbitrary vertex, add it to queue (wait state)
Step #3: Repeat steps # 4 through Step #5 until queue is empty
Step #4: Remove an element from the queue. Process and mark it as visited
(processed state)
Step #5: Enqueue all adjacent vertices of the processed vertex. Go to Step #
3.
The same algorithm may be applied to a subgraph, which contains any
unvisited vertices
‫خان‬ ‫سنور‬ Algorithm Analysis
Example
• Consider the sample directed graph shown below. The steps involved in
performing breadth first search on the graph are depicted in the next set
of diagrams. The execution of algorithm also generates BFS Spanning Tree,
which is shown in bold red lines.
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
• (1) Initially, all the
vertices are in ready
state. For the execution
of BFS algorithm, an
auxiliary data structure
queue is used, which
holds the vertices in
wait state
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
• (2) The vertex a is chosen as
the start vertex . The
neighbors b, n, k of a are
pushed to the queue. The
current status of all of the
vertices is given by the legend
placed at bottom. The vertex
traversed so for is a
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
• (3) The vertex b is removed
from the queue. The vertex c,
neighbor of b, is pushed to the
queue The vertices traversed
so for are: a,b
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
• (4) The vertex k is removed
from the queue. The neighbor j
of vertex k is pushed to the
queue The vertices traversed
so for are: a,b,k
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(5) The vertex n is removed
from the queue. The neighbor l
of vertex n is pushed to the
queue .
• The vertices traversed so for
are: a,b,k,n
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(6) The vertex c is removed from
the queue. The neighbor d of
vertex c is pushed to the queue .
• The vertices traversed so for
are: a,b,k,n,c
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(7) The vertex j is removed from
the queue. The neighbor i of
vertex j is pushed to the queue.
• The vertices traversed so for
are: a,b,k,n,c,j
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(8)The vertex l is removed from
the queue. The neighbors e, m of
vertex l are pushed to the queue.
• The vertices traversed so for
are: a,b,k,n,c,j,l
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(9)The vertex d is removed from
the queue. The vertex d has no
unvisited neighbor.
• The vertices traversed so for
are: a,b,k,n,c,j,l,d
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(10)The vertex i is removed
from the queue. The vertex i has
no unvisited neighbor.
• The vertices traversed so for
are: a,b,k,n,c,j,l,d,i
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(11)The vertex e is removed
from the queue. The neighbor f
of vertex e is pushed to the
queue.
• The vertices traversed so for
are: a,b,k,n,c,j,l,d,I,e.
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(12) The vertex m is removed
from the queue. The neighbor g
of vertex m is pushed to the
queue.
• The vertices traversed so for
are: a,b,k,n,c,j,l,d,I,e,
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(13) The vertex f is removed
from the queue. The vertex f has
no unvisited neighbor
• The vertices traversed so for
are: a,b,k,n,c,j,l,d,I,e,f
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(14)The vertex g is removed
from the queue. The vertex h
neighbor of g is pushed to the
queue.
• The vertices traversed so for
are: a,b,k,n,c,j,l,d,I,e,f,g
‫خان‬ ‫سنور‬ Algorithm Analysis
Solved Example
(15)The vertex h is removed
from the queue. The vertex h
has no unvisited neighbors.
Further, the queue is empty.
The breadth first search
algorithm terminates
‫خان‬ ‫سنور‬ Algorithm Analysis
Implementation
• The BFS implements breadth-first-search procedure by using a queue Q.
The address s of first selected vertex is passed to the method. The
implementation uses an array state[] to keep track of the state of vertices:
READY, WAIT, PROCESSED. The graph is represented by adjacency.
‫خان‬ ‫سنور‬ Algorithm Analysis
Algorithm
BFS(G, s) ► s is address of starting vertex
1. for each vertex u ∈ V[G] –{ s } ►V[G] is vertex set of graph G. V[G]-{s} is the
difference set that excludes initial vertex s.
2. do state[u] ← READY ►All unvisited vertices are assigned READY status
3. state[s] ← WAIT ► Vertex s is pushed to Queue and assigned WAIT status
4. Q ←φ ► Queue is initialized as empty
5. ENQUEUE(Q,s) ► The starting vertex s is added to the Queue
6. while Q ≠φ. ►A loop is created to remove vertices from Queue .
7. do u←DEQUEUE(Q) ► u is the removed vertex
8. for each v ∈ Adj[u] ►All vertices v that are adjacent to vertex u are explored
9. do if state[v] = READY ►If the neighbor vertex v is not visited
10. then state[v]← WAIT ►Then it is assigned WAIT state
11. ENQUEUE(Q,v) And added on to the Queue
12. state[u] ←PROCESSED ►The vertex u removed from the Queue is marked visited
and assigned PROCESSED state
‫خان‬ ‫سنور‬ Algorithm Analysis
Analysis of DFS – Running Time
• The running time for DFS consists of following major components
Ti = Initializing vertices T
Ts = Scanning Adjacency list
• The Graph G(V,E) has |V| vertices and |E| edges. Each vertex is initialized once.
• Therefore,
Ti= |V|
• The scanning of Adjacency list takes place for each dequeued vertex. In BFS all
links are examined. The total time is proportional to the number of edges
scanned. Since |E| is the number of edges in G, in worst case the algorithm
explores all edges , therefore,
Ts = |E|
• Thus, worst case running time is given by time
TDFS= |V|+ |E|= O(|V|+|E|)
‫خان‬ ‫سنور‬ Algorithm Analysis
Topological sorting
The vertices of the graph may represent tasks to be performed, and the edges
may represent constraints that one task must be performed before another;
in this application, a topological ordering is just a valid sequence for the
tasks. A topological ordering is possible if and only if the graph has no
directed cycles, that is, if it is a directed acyclic graph (DAG).
A closely related application of topological sorting algorithms was first
studied in the early 1960s in the context of the PERT (Program evaluation and
review technique) which was designed to analyze and represent the tasks
involved in completing a given project.
‫خان‬ ‫سنور‬ Algorithm Analysis
Kahn’s Algorithm
One of these algorithms, first described by Kahn (1962) works by choosing vertices
in the same order as the eventual topological sort.
• L ← Empty list that will contain the sorted elements S ← Set of all nodes with
no incoming edge
• while S is non-empty do remove a node n from S add
n to tail of L
• for each node m with an edge e from n to m do remove edge e from the
graph
• if m has no other incoming edges then insert m into S
• if graph has edges then
• return error (graph has at least one cycle) else
• return L (a topologically sorted order)
‫خان‬ ‫سنور‬ Algorithm Analysis
Why . . .
• Topological Sorting is a sorting process of items over which partial
ordering is defended.
• Topological sort of a directed acyclic graph(DAG) G is an ordering of the
vertices of G such that for every edge (ei, ej) of G we have i<j {ei appear
before ej in the graph}
• Traverse vertices in increasing order.
• There are two methods to solve it.
• Adjacency Matrix
• Using DFS
‫خان‬ ‫سنور‬ Algorithm Analysis
Example using Adjacency Matrix
1 2 3 4 5 6 7
1 1 1 1
2 1 1 1
3 1 1
4
5 1
6 1
7
2 3
4
7 1
6 5
‫خان‬ ‫سنور‬ Algorithm Analysis
Example using Adjacency Matrix
1 2 3 4 5 6 7
1 1 1 1
2 1 1 1
3 1 1
4
5 1
6 1
7
2 3
4
7 1
6 5
1 2 3 4 5 6 7
‫خان‬ ‫سنور‬ Algorithm Analysis
Example using Adjacency Matrix - Prove
1 2 3 4 5 6 7
1 1 1 1
2 1 1 1
3 1 1
4
5 1
6 1
7
2 3
4
7 1
6 5
1 2 3 4 5 6 7
• 1 should appear before 4, 5, 6 so it is true
• 2 should appear before 3, 5 and 6. it is also true
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited SetA B
E D
F G G
C
Sorted Set
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
H
E
A B
E D
H F G
C
Sorted Set
H
Start From Any Node, In our Example We are starting From E
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
G
F
H
E
A B
E D
F G
C
Sorted Set
G
H
Start From Any Node, In our Example We are starting From E
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
G
F
H
E
A B
E D
F G
C
Sorted Set
F
G
H
Start From Any Node, In our Example We are starting From E
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
G
F
H
E
A B
E D
F G
C
Sorted Set
E
F
G
H
Start From Any Node, In our Example We are starting From E
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
C
A
G
F
H
E
A B
E D
F G
C
Sorted Set
C
E
F
G
H
Start From Any Node, In our Example We are starting From E
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
C
A
G
F
H
E
A B
E D
F G
C
Sorted Set
A
C
E
F
G
H
Start From Any Node, In our Example We are starting From E
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
D
B
C
A
G
F
H
E
A B
E D
F G
C
Sorted Set
D
A
C
E
F
G
H
Start From Any Node, In our Example We are starting From E
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
D
B
C
A
G
F
H
E
A B
E D
F G
C
Sorted Set
B
D
A
C
E
F
G
H
Start From Any Node, In our Example We are starting From E
‫خان‬ ‫سنور‬ Algorithm Analysis
Example Using DFS(Depth First Search)
Visited Set
D
B
C
A
G
F
H
E
A B
E D
F G
C
Sorted Set
B
D
A
C
E
F
G
H
Start From Any Node, In our Example We are starting From E
Sorted List B D A C E F G H
‫خان‬ ‫سنور‬ Algorithm Analysis
Applications of this type arise in instruction scheduling (is a compiler
optimization, which improves performance on machines with instruction
pipelines) when re-computing formula values in spreadsheets, determining
the order of compilation tasks to perform in makefiles. It is also used to
decide in which order to load tables with foreign keys in databases.
Applications
1 de 90

Recomendados

Graph 2 por
Graph 2Graph 2
Graph 2International Islamic University
140 vistas83 diapositivas
Graph 3 por
Graph 3Graph 3
Graph 3International Islamic University
160 vistas35 diapositivas
Merge sort por
Merge sortMerge sort
Merge sortInternational Islamic University
93 vistas21 diapositivas
Lecture24 por
Lecture24Lecture24
Lecture24Dr Sandeep Kumar Poonia
3.4K vistas50 diapositivas
3.8 quicksort por
3.8 quicksort3.8 quicksort
3.8 quicksortKrish_ver2
4.9K vistas15 diapositivas
Quick sort Algorithm Discussion And Analysis por
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisSNJ Chaudhary
6.2K vistas30 diapositivas

Más contenido relacionado

La actualidad más candente

Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm) por
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)Mohanlal Sukhadia University (MLSU)
3.9K vistas36 diapositivas
Prestation_ClydeShen por
Prestation_ClydeShenPrestation_ClydeShen
Prestation_ClydeShenClyde Shen
212 vistas106 diapositivas
Greedy algorithm por
Greedy algorithmGreedy algorithm
Greedy algorithmInternational Islamic University
6.4K vistas48 diapositivas
Quicksort por
QuicksortQuicksort
QuicksortGayathri Gaayu
3.8K vistas20 diapositivas
Problems in parallel computations of tree functions por
Problems in parallel computations of tree functionsProblems in parallel computations of tree functions
Problems in parallel computations of tree functionsDr Sandeep Kumar Poonia
995 vistas48 diapositivas
a brief introduction to Arima por
a brief introduction to Arimaa brief introduction to Arima
a brief introduction to ArimaYue Xiangnan
70 vistas29 diapositivas

La actualidad más candente(20)

Prestation_ClydeShen por Clyde Shen
Prestation_ClydeShenPrestation_ClydeShen
Prestation_ClydeShen
Clyde Shen212 vistas
a brief introduction to Arima por Yue Xiangnan
a brief introduction to Arimaa brief introduction to Arima
a brief introduction to Arima
Yue Xiangnan70 vistas
Algorithm: Quick-Sort por Tareq Hasan
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan17.9K vistas
On the Numerical Solution of Differential Equations por Kyle Poe
On the Numerical Solution of Differential EquationsOn the Numerical Solution of Differential Equations
On the Numerical Solution of Differential Equations
Kyle Poe1.6K vistas
Lecture 4 asymptotic notations por jayavignesh86
Lecture 4   asymptotic notationsLecture 4   asymptotic notations
Lecture 4 asymptotic notations
jayavignesh861.3K vistas
Basic terminologies & asymptotic notations por Rajendran
Basic terminologies & asymptotic notationsBasic terminologies & asymptotic notations
Basic terminologies & asymptotic notations
Rajendran 1.2K vistas
Lecture 5: Asymptotic analysis of algorithms por Vivek Bhargav
Lecture 5: Asymptotic analysis of algorithmsLecture 5: Asymptotic analysis of algorithms
Lecture 5: Asymptotic analysis of algorithms
Vivek Bhargav2.2K vistas
Asymptotic Notation and Data Structures por Amrinder Arora
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data Structures
Amrinder Arora13.6K vistas
Presentation on binary search, quick sort, merge sort and problems por Sumita Das
Presentation on binary search, quick sort, merge sort  and problemsPresentation on binary search, quick sort, merge sort  and problems
Presentation on binary search, quick sort, merge sort and problems
Sumita Das1.2K vistas

Similar a Graph 1

Graph Theory por
Graph TheoryGraph Theory
Graph TheoryRashmi Bhat
299 vistas78 diapositivas
ppt 1.pptx por
ppt 1.pptxppt 1.pptx
ppt 1.pptxShasidharaniD
5 vistas82 diapositivas
Unit 9 graph por
Unit   9 graphUnit   9 graph
Unit 9 graphDabbal Singh Mahara
222 vistas43 diapositivas
Unit ix graph por
Unit   ix    graph Unit   ix    graph
Unit ix graph Tribhuvan University
988 vistas42 diapositivas
UNIT III.pptx por
UNIT III.pptxUNIT III.pptx
UNIT III.pptxSwarndeviKm
29 vistas74 diapositivas

Similar a Graph 1(20)

Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM) por Abdul Naqashbandi
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
Abdul Naqashbandi48 vistas
Graphs (Models & Terminology) por zunaira saleem
Graphs (Models & Terminology)Graphs (Models & Terminology)
Graphs (Models & Terminology)
zunaira saleem127 vistas
Graphs in data structure por hamza javed
Graphs in data structureGraphs in data structure
Graphs in data structure
hamza javed1.8K vistas
Graphs in Data Structure por hafsa komal
 Graphs in Data Structure Graphs in Data Structure
Graphs in Data Structure
hafsa komal2.2K vistas

Más de International Islamic University

Hash tables por
Hash tablesHash tables
Hash tablesInternational Islamic University
2.2K vistas59 diapositivas
Binary Search Tree por
Binary Search TreeBinary Search Tree
Binary Search TreeInternational Islamic University
1.3K vistas74 diapositivas
Dynamic programming por
Dynamic programmingDynamic programming
Dynamic programmingInternational Islamic University
434 vistas21 diapositivas
Quick sort por
Quick sortQuick sort
Quick sortInternational Islamic University
1.3K vistas51 diapositivas
Linear timesorting por
Linear timesortingLinear timesorting
Linear timesortingInternational Islamic University
51 vistas14 diapositivas
Facial Expression Recognitino por
Facial Expression RecognitinoFacial Expression Recognitino
Facial Expression RecognitinoInternational Islamic University
7.3K vistas53 diapositivas

Más de International Islamic University(20)

Último

Women from Hackney’s History: Stoke Newington by Sue Doe por
Women from Hackney’s History: Stoke Newington by Sue DoeWomen from Hackney’s History: Stoke Newington by Sue Doe
Women from Hackney’s History: Stoke Newington by Sue DoeHistory of Stoke Newington
141 vistas21 diapositivas
Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation) por
 Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation) Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation)
Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation)AnshulDewangan3
316 vistas12 diapositivas
Education and Diversity.pptx por
Education and Diversity.pptxEducation and Diversity.pptx
Education and Diversity.pptxDrHafizKosar
118 vistas16 diapositivas
Universe revised.pdf por
Universe revised.pdfUniverse revised.pdf
Universe revised.pdfDrHafizKosar
112 vistas26 diapositivas
Solar System and Galaxies.pptx por
Solar System and Galaxies.pptxSolar System and Galaxies.pptx
Solar System and Galaxies.pptxDrHafizKosar
85 vistas26 diapositivas
discussion post.pdf por
discussion post.pdfdiscussion post.pdf
discussion post.pdfjessemercerail
120 vistas1 diapositiva

Último(20)

Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation) por AnshulDewangan3
 Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation) Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation)
Compare the flora and fauna of Kerala and Chhattisgarh ( Charttabulation)
AnshulDewangan3316 vistas
Education and Diversity.pptx por DrHafizKosar
Education and Diversity.pptxEducation and Diversity.pptx
Education and Diversity.pptx
DrHafizKosar118 vistas
Universe revised.pdf por DrHafizKosar
Universe revised.pdfUniverse revised.pdf
Universe revised.pdf
DrHafizKosar112 vistas
Solar System and Galaxies.pptx por DrHafizKosar
Solar System and Galaxies.pptxSolar System and Galaxies.pptx
Solar System and Galaxies.pptx
DrHafizKosar85 vistas
Are we onboard yet University of Sussex.pptx por Jisc
Are we onboard yet University of Sussex.pptxAre we onboard yet University of Sussex.pptx
Are we onboard yet University of Sussex.pptx
Jisc77 vistas
UWP OA Week Presentation (1).pptx por Jisc
UWP OA Week Presentation (1).pptxUWP OA Week Presentation (1).pptx
UWP OA Week Presentation (1).pptx
Jisc74 vistas
Lecture: Open Innovation por Michal Hron
Lecture: Open InnovationLecture: Open Innovation
Lecture: Open Innovation
Michal Hron96 vistas
11.28.23 Social Capital and Social Exclusion.pptx por mary850239
11.28.23 Social Capital and Social Exclusion.pptx11.28.23 Social Capital and Social Exclusion.pptx
11.28.23 Social Capital and Social Exclusion.pptx
mary850239281 vistas
Scope of Biochemistry.pptx por shoba shoba
Scope of Biochemistry.pptxScope of Biochemistry.pptx
Scope of Biochemistry.pptx
shoba shoba124 vistas
Class 10 English lesson plans por TARIQ KHAN
Class 10 English  lesson plansClass 10 English  lesson plans
Class 10 English lesson plans
TARIQ KHAN257 vistas
The basics - information, data, technology and systems.pdf por JonathanCovena1
The basics - information, data, technology and systems.pdfThe basics - information, data, technology and systems.pdf
The basics - information, data, technology and systems.pdf
JonathanCovena188 vistas
Community-led Open Access Publishing webinar.pptx por Jisc
Community-led Open Access Publishing webinar.pptxCommunity-led Open Access Publishing webinar.pptx
Community-led Open Access Publishing webinar.pptx
Jisc74 vistas
Narration lesson plan.docx por TARIQ KHAN
Narration lesson plan.docxNarration lesson plan.docx
Narration lesson plan.docx
TARIQ KHAN104 vistas
Psychology KS5 por WestHatch
Psychology KS5Psychology KS5
Psychology KS5
WestHatch77 vistas
Use of Probiotics in Aquaculture.pptx por AKSHAY MANDAL
Use of Probiotics in Aquaculture.pptxUse of Probiotics in Aquaculture.pptx
Use of Probiotics in Aquaculture.pptx
AKSHAY MANDAL89 vistas

Graph 1

  • 1. Sunawar Khan Islamia University of Bahawalpur Bahawalnagar Campus Analysis o f Algorithm
  • 2. ‫خان‬ ‫سنور‬ Algorithm Analysis DFS and BFS Graph Traversal Representation of Graph Minimum Spanning Tree Topological Sort Contents
  • 3. ‫خان‬ ‫سنور‬ Algorithm Analysis Topics • Graph Terminology • Graph Representation • Matrix Representation • Linked List Representation • Depth First Search Algorithm(DFS) • Strategy • Application • Analysis • Breadth First Search Algorithm(BFS) • Strategy • Application • Analysis
  • 4. ‫خان‬ ‫سنور‬ Algorithm Analysis What is Graph • A graph G = (V, E) is a set of vertices V and a set of edges E, where • E ⊆ V x V(Subset of cross-product of vertices called binary relation) • Example: Let G = (V, E) where • V = {a, b, c, d} • E = {(a, b) , (a, d) , (b, c) , (b, a) , (c, d) , (b, d) , (d, d)} • The number of vertices and edges are given by the cardinalities |V| and |E| of the corresponding sets. The sample graph consists of four vertices and seven edges. Thus, |V| = 4, |E| = 7 • Graph are usually represented by pictorial diagrams. The vertices can be shown as labeled CIRCLE or RECTANGLES. The edges are depicts arcs lines. Except for some applications, in which distances among vertices are important, the positions of the vertices are in general, immaterial. Thus, graphs can be shown pictorially in several ways.
  • 5. ‫خان‬ ‫سنور‬ Algorithm Analysis Basic Terminologies • Mathematical graphs can be represented in data structure. We can represent a graph using an array of vertices and a two-dimensional array of edges. Before we proceed further, let's familiarize ourselves with some important terms − • Vertex • Edges • Adjacency • Path
  • 6. ‫خان‬ ‫سنور‬ Algorithm Analysis Vertex • Each node of the graph is represented as a vertex. In the following example, the labeled circle represents vertices. Thus, A to G are vertices. We can represent them using an array as shown in the following image. Here A can be identified by index 0. B can be identified using index 1 and so on.
  • 7. ‫خان‬ ‫سنور‬ Algorithm Analysis Edges • Edge represents a path between two vertices or a line between two vertices. In the following example, the lines from A to B, B to C, and so on represents edges. We can use a two-dimensional array to represent an array as shown in the following image. Here AB can be represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping other combinations as 0.
  • 8. ‫خان‬ ‫سنور‬ Algorithm Analysis Adjacency • Two node or vertices are adjacent if they are connected to each other through an edge. In the following example, B is adjacent to A, C is adjacent to B, and so on.
  • 9. ‫خان‬ ‫سنور‬ Algorithm Analysis Path • Path represents a sequence of edges between the two vertices. In the following example, ABCD represents a path from A to D.
  • 10. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph – Undirected Graph • A graph G = (V,E) with vertex set V = {v1, v2, v3, . . . , vn} is called undirected if (vi, vj) = (vj,vi) for i ≠ j • An undirected graph is sometimes referred to as undigraph. • Inn pictorial representation of undirected graph, the edges are not assigned any direction. • Example:- Figure shows an undirected graph. • G=(V. E) • V ={a, b, c, d, e, f} • E = {(a, b) , (a, d) , (a, f) , (b, c) , (b, e) , (c, f) , (c, d) , (d, e) , (e, f)}
  • 11. ‫خان‬ ‫سنور‬ Algorithm Analysis Undirected Graph – Complete • A graph which has links among all of the vertices in a graph is referred t as complete. • Example: The figure shows complete graph • An undirected complete graph, with n vertices, has n(n-1)/2 edges. The spaces complexity graph is O(n2). • A complete graph is dense. By contrast, a graph with space complexity O(n log n) is called sparse
  • 12. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph – Directed Graph • A graph G = (V,E) with vertex set V = {v1, v2, v3, . . . , vn} is called undirected if (vi, vj) = (vj,vi) for i ≠ j • In other words, the edges (vi, vj) and (vj, vi), associated with any pair of verties vi, vj are considered distinct. In pictorial representation show here wit arrows. • The directed graph is often referred to digraph or network.
  • 13. ‫خان‬ ‫سنور‬ Algorithm Analysis Directed Graph - Complete • A complete directed graph has links among all of the vertices. • Example:- The figure shows a directed complete graph. • A complete directed graph with n vertices has n(n-1) edges.
  • 14. ‫خان‬ ‫سنور‬ Algorithm Analysis Weighted Graphs- Undirected • A graph in which labels or values w1, w2, w3, . . . are associated with edges is called weighted graph. Weights are typically costs or distances in different application of graphs. • Example:- The figure shows an example of weighted undirected graph.
  • 15. ‫خان‬ ‫سنور‬ Algorithm Analysis Weighted Graph- Directed • A weighted graph can also be directed. The weights attached to the edges to the edges between the same pair of vertices may, in general, be different • Example :- The figure below shows an example of the directed weighted graph. Note that weight of edged from vertex a to vertex b is 73 and that from vertex b too vertex a is 35.
  • 16. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Paths • A path is a sequence of andjacent vertices. Two vertices are called adjacent if they are link oor connecting edge. The path is denoted by enclosing the vertices is a pair of square brackets. In path, the vertices may repeated. • Example: The figure below depicts a path P = [a, b, g, d, e, i, h ]in a sample graph. The path is shown in bold red lines. • The number of edges connecting the vertices in a path is called path length. The path length in the above example is 6.
  • 17. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Path – Simple Path • A path is called simple if no vertices are repeated; otherwise, the path is referred to as non-simple. • Example: The figures below show simple and non-simple paths in a graph. The path P1=[ a, c, g, d, f ] is simple. The path P2=[a, c, g, d, f, c, b, f ] is non-simple, because it passes through vertices c, f twice.
  • 18. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Path - Loops • A loop is special path that originates and terminates at a single node, and does not pass through other vertices. • Example: The figure depicts two loops in a graph, at vertices a and c • The loops are important in certain some applications. For example, loops represent certain states in Finite State Automat
  • 19. ‫خان‬ ‫سنور‬ Algorithm Analysis Cyclic and Acyclic Graph • A path that originates and terminates at the same vertex, and links two or more vertices, is called cycle. If a graph contains a cycle it is called cyclic. By contrast, a graph which contains no cycles is known as acyclic. • Example: In diagram (i), the path P=[b, c, d, b] is a cycle. The diagram (ii) represents a acyclic graph.
  • 20. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Representation – Adjacency Matrix • One of the standard ways of representing a graph uses a matrix to denote links between pairs of vertices in a graph. The matrix is known as adjacency matrix. • The adjacency matrix can be defined mathematically. Let G=(V,E) be a graph, with V={v1,v2,……vn}, and E={(v1,v2),(v1,v3)….}where n=|V|. The adjacency matrix A=[aij] as • 𝑎𝑖𝑗 = ቊ 1 𝑖𝑓 𝑣𝑡, 𝑣𝑗 ∈ 𝐸 0 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒 • The definition implies that entry in the ith row and jth column of the matrix is 1 • if a link exists between the ith and jth vertex; otherwise, it is 0. • The size adjacency matrix is with vertex set V is |V|x|V| . Thus space complexity is θ(|V|2)
  • 21. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Representation – Adjacency Matrix • Example : Figure (i) shows a sample directed graph. Figure (ii) shows the adjacency matrix for the graph.
  • 22. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Representation- Adjacency Link List • A graph can also be represented using linked lists. The list representation consists of an array of linked lists, each corresponding to one vertex. The list stores all of the vertices that are linked to a given vertex. • Let G=(V,E) be a graph, and Adj(u) be the linked list corresponding to vertex u, then for all v, v ∈Adj(u), if (u ,v ) ∈E. • The vertices belonging to Adj(u) are called neighbors of vertex u, or adjacent vertices.
  • 23. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Representation – Linked List • Example:- The diagram below show a sample graph and its linked list representation.
  • 24. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Traversal • In graph traversal, all vertices are visited once. Depending on the application, the data and keys are accessed and processed further. For example, the traversal procedure can be used to list keys stored in the vertices The two important procedures for graph traversal are: 1) Depth First Search (DFS) 2) Breadth First Search (BFS) • The DFS and algorithms can be used to traverse both directed and undirected graphs
  • 25. ‫خان‬ ‫سنور‬ Algorithm Analysis Depth First Search • The Depth First Search (DFS) systematically visits all vertices of a graph. Initially, a start vertex is chosen, and its neighbors are explored. Then neighbors and of neighbors are explored. This process is continued till the remotest neighbor of the start vertex is reached, which is called the dead end. The algorithm then backtracks to the start vertex and on the way back lists all of the vertices in depth first search order. The depth first search algorithm belongs to the class of backtracking algorithms. • A stack is used to implement the DFS procedure. The stack keeps track of vertices traversed . For this purpose , the three states of vertices are designated as ready, wait and processed, defined as follows : • All vertices are initially in the ready state • A vertex pushed on to the stack, is in the wait state • A vertex popped off the stack is in the processed state
  • 26. ‫خان‬ ‫سنور‬ Algorithm Analysis Algorithm • The Depth First Search (DFS) for a connected graph consists of the following steps: • Step #1: Initialize all vertices to mark as unvisited (ready state) • Step #2: Select an arbitrary vertex, push it to stack (wait state) • Step #3: Repeat steps # 4 through Step #5 until the stack is empty • Step #4: Pop off an element from the stack. Process and mark it as visited (processed) • Step #5: Push to stack adjacent vertices of the processed vertex. Go toStep # 3. • The same procedure is applied to a subgraph, which may contain any unvisited vertices.
  • 27. ‫خان‬ ‫سنور‬ Algorithm Analysis DFS – Spanning Tree • Apart from extracting information stored in vertices, the DFS can be used to construct special tree called DFS Spanning trees The Spanning trees are useful in investigating important properties of the graphs and subgraphs • During the DFS, a spanning tree is constructed by linking together a vertex that is visited for the first time to the vertex from which it is reached. The links are called
  • 28. ‫خان‬ ‫سنور‬ Algorithm Analysis Example • Consider the sample directed graph shown below. The steps involved in Depth First Search are depicted in the next set of diagrams As the algorithm proceeds, the depth first spanning tree is also generated.
  • 29. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example
  • 45. ‫خان‬ ‫سنور‬ Algorithm Analysis Applications • Some important applications of DFS are (i) Checking connectivity of a graph (ii) Checking accessibility of vertices from a given vertex (iii) Checking cyclicity/ acyclicity of a graph • Graph connectivity and cyclicity are illustrated by the following examples
  • 46. ‫خان‬ ‫سنور‬ Algorithm Analysis Graph Connectivity • An undirected graph is not connected if the DFS algorithm terminates before all of the vertices have been visited. The unvisited vertices form one or more subgraphs • Example: Figure (i) shows a sample graph. Figure (ii) provides a DFS tree. The vertices M.P,R,Q,D remain unvisited and constitute a disconnected subgraph.
  • 47. ‫خان‬ ‫سنور‬ Algorithm Analysis Subgraph Accessibility • In a directed graph, all the vertices may have links, but may not be accessible from given vertex. The inaccessible vertices can be explored by using DFS • Example: Figure (i) shows a sample directed graph. Figure (ii) provides a DFS tree. The vertices L,G,A remain unvisited and constitute subgraph whose vertices are not accessible from initial vertex M
  • 48. ‫خان‬ ‫سنور‬ Algorithm Analysis Acyclic Graph • An undirected graph is acyclic ( has no cycles) if the DFS spanning has no back edges • Example: Figure (i) shows a sample graph . Figure (ii) contains a DFS Spanning Tree, which has no back edges. The graph is therefore acyclic
  • 49. ‫خان‬ ‫سنور‬ Algorithm Analysis Cyclic Graph • An undirected graph is cyclic if the DFS spanning has back edges • Example: Figure (i) shows a sample graph . Figure (ii) contains the DFS spanning tree, which has back edges shown in blue color. The graph is therefore cyclic
  • 50. ‫خان‬ ‫سنور‬ Algorithm Analysis Implementation • The DFS implements depth-first-search procedure by using a stack S. The address s of first selected vertex is passed to the method. The implementation uses an array state[] which stores status of vertices as READY, WAIT, PROCESSED. The graph is represented by adjacency list Adj . The notation Adj[u] denotes a neighbor of vertex u
  • 51. ‫خان‬ ‫سنور‬ Algorithm Analysis Algorithm DFS(G, s) ► s is address of starting vertex 1. for each vertex u ∈ V[G] –{ s } ►V[G] is vertex set of graph G. V[G]-{s} is the difference set that excludes initial vertex s. 2. do state[u] ← READY ►All unvisited vertices are assigned READY status 3. state[s] ← WAIT ► Vertex s is pushed to stack and assigned WAIT status 4. P ←φ ► Stack P is initialized as empty 5. PUSH(S,s) ► The starting vertex s is added to the stack 6. while S ≠φ. ►A loop is created to pop off vertices . 7. do u←POP(S) ► u is the popped vertex 8. for each v ∈ Adj[u] ►All vertices v that are adjacent to vertex u are explored 9. do if state[v] = READY ►If the neighbor vertex v is not visited 10. then state[v]← WAIT ►Then it is assigned WAIT state 11. PUSH(S,v) Pushed on to the stack S 12. state[u] ←PROCESSED ►The vertex u popped off the stack is marked visited and assigned PROCESSED state
  • 52. ‫خان‬ ‫سنور‬ Algorithm Analysis Analysis of DFS – Running Time • The running time for DFS consists of following major components Ti = Initializing vertices T Ts = Scanning Adjacency list • The Graph G(V,E) has |V| vertices and |E| edges. Each vertex is initialized once. • Therefore, Ti= |V| • The scanning of Adjacency list takes place for each vertex. The total time is • proportional to the number of edges scanned. Since |E| is the number of edges in G, in • worst case the algorithm explores all edges , therefore, Ts = |E| • Thus, worst case running time is given by time TDFS= |V|+ |E|= O(|V|+|E|)
  • 53. ‫خان‬ ‫سنور‬ Algorithm Analysis Breadth First Strategy - Strategy • The Breadth First Search(BFS) is one of the standard graph traversal methods. Each node is visited once only. The method proceeds by visiting all immediate neighbors ( vertices one edge away), then visiting neighbor’s neighbors (vertices two edges away), and so forth, until all reachable vertices have been visited. • If a graph has any subgraph(which is not reachable from the initial vertex), the procedure may be re-started by choosing a vertex from the unvisited subgraph. • A queue is used to implement the BFS procedure. It keeps track of vertices to be visited next. A vertex pushed to the queue is said to be in ready state. • An enqueued vertex is said be in wait state. The dequeued vertex is referred to as • . • The queue is initialized with the address of a starting vertex.
  • 54. ‫خان‬ ‫سنور‬ Algorithm Analysis Algorithm The Breadth First Search (BFS) for a connected graph consists of following steps: Step #1: Initialize all vertices to mark as unvisited (ready state) Step #2: Select an arbitrary vertex, add it to queue (wait state) Step #3: Repeat steps # 4 through Step #5 until queue is empty Step #4: Remove an element from the queue. Process and mark it as visited (processed state) Step #5: Enqueue all adjacent vertices of the processed vertex. Go to Step # 3. The same algorithm may be applied to a subgraph, which contains any unvisited vertices
  • 55. ‫خان‬ ‫سنور‬ Algorithm Analysis Example • Consider the sample directed graph shown below. The steps involved in performing breadth first search on the graph are depicted in the next set of diagrams. The execution of algorithm also generates BFS Spanning Tree, which is shown in bold red lines.
  • 56. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example • (1) Initially, all the vertices are in ready state. For the execution of BFS algorithm, an auxiliary data structure queue is used, which holds the vertices in wait state
  • 57. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example • (2) The vertex a is chosen as the start vertex . The neighbors b, n, k of a are pushed to the queue. The current status of all of the vertices is given by the legend placed at bottom. The vertex traversed so for is a
  • 58. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example • (3) The vertex b is removed from the queue. The vertex c, neighbor of b, is pushed to the queue The vertices traversed so for are: a,b
  • 59. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example • (4) The vertex k is removed from the queue. The neighbor j of vertex k is pushed to the queue The vertices traversed so for are: a,b,k
  • 60. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (5) The vertex n is removed from the queue. The neighbor l of vertex n is pushed to the queue . • The vertices traversed so for are: a,b,k,n
  • 61. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (6) The vertex c is removed from the queue. The neighbor d of vertex c is pushed to the queue . • The vertices traversed so for are: a,b,k,n,c
  • 62. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (7) The vertex j is removed from the queue. The neighbor i of vertex j is pushed to the queue. • The vertices traversed so for are: a,b,k,n,c,j
  • 63. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (8)The vertex l is removed from the queue. The neighbors e, m of vertex l are pushed to the queue. • The vertices traversed so for are: a,b,k,n,c,j,l
  • 64. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (9)The vertex d is removed from the queue. The vertex d has no unvisited neighbor. • The vertices traversed so for are: a,b,k,n,c,j,l,d
  • 65. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (10)The vertex i is removed from the queue. The vertex i has no unvisited neighbor. • The vertices traversed so for are: a,b,k,n,c,j,l,d,i
  • 66. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (11)The vertex e is removed from the queue. The neighbor f of vertex e is pushed to the queue. • The vertices traversed so for are: a,b,k,n,c,j,l,d,I,e.
  • 67. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (12) The vertex m is removed from the queue. The neighbor g of vertex m is pushed to the queue. • The vertices traversed so for are: a,b,k,n,c,j,l,d,I,e,
  • 68. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (13) The vertex f is removed from the queue. The vertex f has no unvisited neighbor • The vertices traversed so for are: a,b,k,n,c,j,l,d,I,e,f
  • 69. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (14)The vertex g is removed from the queue. The vertex h neighbor of g is pushed to the queue. • The vertices traversed so for are: a,b,k,n,c,j,l,d,I,e,f,g
  • 70. ‫خان‬ ‫سنور‬ Algorithm Analysis Solved Example (15)The vertex h is removed from the queue. The vertex h has no unvisited neighbors. Further, the queue is empty. The breadth first search algorithm terminates
  • 71. ‫خان‬ ‫سنور‬ Algorithm Analysis Implementation • The BFS implements breadth-first-search procedure by using a queue Q. The address s of first selected vertex is passed to the method. The implementation uses an array state[] to keep track of the state of vertices: READY, WAIT, PROCESSED. The graph is represented by adjacency.
  • 72. ‫خان‬ ‫سنور‬ Algorithm Analysis Algorithm BFS(G, s) ► s is address of starting vertex 1. for each vertex u ∈ V[G] –{ s } ►V[G] is vertex set of graph G. V[G]-{s} is the difference set that excludes initial vertex s. 2. do state[u] ← READY ►All unvisited vertices are assigned READY status 3. state[s] ← WAIT ► Vertex s is pushed to Queue and assigned WAIT status 4. Q ←φ ► Queue is initialized as empty 5. ENQUEUE(Q,s) ► The starting vertex s is added to the Queue 6. while Q ≠φ. ►A loop is created to remove vertices from Queue . 7. do u←DEQUEUE(Q) ► u is the removed vertex 8. for each v ∈ Adj[u] ►All vertices v that are adjacent to vertex u are explored 9. do if state[v] = READY ►If the neighbor vertex v is not visited 10. then state[v]← WAIT ►Then it is assigned WAIT state 11. ENQUEUE(Q,v) And added on to the Queue 12. state[u] ←PROCESSED ►The vertex u removed from the Queue is marked visited and assigned PROCESSED state
  • 73. ‫خان‬ ‫سنور‬ Algorithm Analysis Analysis of DFS – Running Time • The running time for DFS consists of following major components Ti = Initializing vertices T Ts = Scanning Adjacency list • The Graph G(V,E) has |V| vertices and |E| edges. Each vertex is initialized once. • Therefore, Ti= |V| • The scanning of Adjacency list takes place for each dequeued vertex. In BFS all links are examined. The total time is proportional to the number of edges scanned. Since |E| is the number of edges in G, in worst case the algorithm explores all edges , therefore, Ts = |E| • Thus, worst case running time is given by time TDFS= |V|+ |E|= O(|V|+|E|)
  • 74. ‫خان‬ ‫سنور‬ Algorithm Analysis Topological sorting The vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). A closely related application of topological sorting algorithms was first studied in the early 1960s in the context of the PERT (Program evaluation and review technique) which was designed to analyze and represent the tasks involved in completing a given project.
  • 75. ‫خان‬ ‫سنور‬ Algorithm Analysis Kahn’s Algorithm One of these algorithms, first described by Kahn (1962) works by choosing vertices in the same order as the eventual topological sort. • L ← Empty list that will contain the sorted elements S ← Set of all nodes with no incoming edge • while S is non-empty do remove a node n from S add n to tail of L • for each node m with an edge e from n to m do remove edge e from the graph • if m has no other incoming edges then insert m into S • if graph has edges then • return error (graph has at least one cycle) else • return L (a topologically sorted order)
  • 76. ‫خان‬ ‫سنور‬ Algorithm Analysis Why . . . • Topological Sorting is a sorting process of items over which partial ordering is defended. • Topological sort of a directed acyclic graph(DAG) G is an ordering of the vertices of G such that for every edge (ei, ej) of G we have i<j {ei appear before ej in the graph} • Traverse vertices in increasing order. • There are two methods to solve it. • Adjacency Matrix • Using DFS
  • 77. ‫خان‬ ‫سنور‬ Algorithm Analysis Example using Adjacency Matrix 1 2 3 4 5 6 7 1 1 1 1 2 1 1 1 3 1 1 4 5 1 6 1 7 2 3 4 7 1 6 5
  • 78. ‫خان‬ ‫سنور‬ Algorithm Analysis Example using Adjacency Matrix 1 2 3 4 5 6 7 1 1 1 1 2 1 1 1 3 1 1 4 5 1 6 1 7 2 3 4 7 1 6 5 1 2 3 4 5 6 7
  • 79. ‫خان‬ ‫سنور‬ Algorithm Analysis Example using Adjacency Matrix - Prove 1 2 3 4 5 6 7 1 1 1 1 2 1 1 1 3 1 1 4 5 1 6 1 7 2 3 4 7 1 6 5 1 2 3 4 5 6 7 • 1 should appear before 4, 5, 6 so it is true • 2 should appear before 3, 5 and 6. it is also true
  • 80. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited SetA B E D F G G C Sorted Set
  • 81. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set H E A B E D H F G C Sorted Set H Start From Any Node, In our Example We are starting From E
  • 82. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set G F H E A B E D F G C Sorted Set G H Start From Any Node, In our Example We are starting From E
  • 83. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set G F H E A B E D F G C Sorted Set F G H Start From Any Node, In our Example We are starting From E
  • 84. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set G F H E A B E D F G C Sorted Set E F G H Start From Any Node, In our Example We are starting From E
  • 85. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set C A G F H E A B E D F G C Sorted Set C E F G H Start From Any Node, In our Example We are starting From E
  • 86. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set C A G F H E A B E D F G C Sorted Set A C E F G H Start From Any Node, In our Example We are starting From E
  • 87. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set D B C A G F H E A B E D F G C Sorted Set D A C E F G H Start From Any Node, In our Example We are starting From E
  • 88. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set D B C A G F H E A B E D F G C Sorted Set B D A C E F G H Start From Any Node, In our Example We are starting From E
  • 89. ‫خان‬ ‫سنور‬ Algorithm Analysis Example Using DFS(Depth First Search) Visited Set D B C A G F H E A B E D F G C Sorted Set B D A C E F G H Start From Any Node, In our Example We are starting From E Sorted List B D A C E F G H
  • 90. ‫خان‬ ‫سنور‬ Algorithm Analysis Applications of this type arise in instruction scheduling (is a compiler optimization, which improves performance on machines with instruction pipelines) when re-computing formula values in spreadsheets, determining the order of compilation tasks to perform in makefiles. It is also used to decide in which order to load tables with foreign keys in databases. Applications