DFS Unit 4
DFS Unit 4
UNIT – IV
Graphs
Graphs: Definition
• A graph G = (V,E) is composed of:
V: set of vertices
E: set of edges connecting the vertices in V
• An edge e = (u,v) is a pair of vertices
• Example:
V= {a,b,c,d,e}
E= {(a,b),(a,c),(a,d),(b,e),(c,d),(c,e),(d,e)}
Types of Graph:-
• An undirected graph is one in which the pair of vertices in a edge is unordered,
(v0, v1) = (v1,v0)
Example, Graph 1 shown above.
• A directed graph is one in which each edge is a directed pair of vertices, <v0,
v1> != <v1,v0>
Example,
• Path: Sequence of vertices v1,v2,. . .vk such that consecutive vertices vi and
vi+1 are adjacent.
Example, consider same graph 1. The paths can be:-
Cycle: is a simple path, except that the last vertex is the same as the firstvertex.
Example, consider same graph 1. A cycle can be:-
Complete graph: one in which all pairs of vertices are adjacent. Total numberof edges in
complete graph is - m = n(n -1)/2, where m is number of edges andn are vertices.
n=5
m = 5 * (5-1)/2 = 10
Graph Representation:-
Adjacency Matrix
oLet G = (V, E) be a graph with n vertices.
oThe adjacency matrix of G is a two-dimensionaln by n array, say adj_mat
oIf the edge (vi, vj) is in E(G), adj_mat[i][j]=1
oIf there is no such edge in E(G), adj_mat[i][j]=0
The adjacency matrix for an undirected graph is symmetric; the
adjacency matrix for a digraph need not be symmetric
oExample,
Adjacency Lists
oAn array of linked lists is used. Size of the array is equal to number
of vertices. Let the array be array[]. An entry array[i] represents the
linked list of vertices adjacent to the ith vertex. This representation
can also be used to represent a weighted graph. The weights of
edges can be stored in nodes of linked lists.
oExample,
This representation takes O(|V | + |E|) space.
Traversal in Graphs
BFS (Breadth First Traversal):-
oIn this method, After visiting a vertex v, we must visit all its
adjacent vertices w1, w2, w3, ..., before going down next level to
visit vertices adjacent to w1 etc.
oThe method can be implemented using a queue.
oA boolean array is used to ensure that a vertex is enqueued only
once.
oAlgorithm:-
enqueue the starting vertex
while(queue is not empty){
dequeue a vertex v from the queue;
visit v.
enqueue vertices adjacent to v that were never enqueued;
}
DFS
DFS (Depth First Traversal)
o In this method, After visiting a vertex v, which is adjacent to w1,w2, w3….., Next we visit
one of v's adjacent vertices, w1 say.Next, we visit all vertices adjacent to w1 before coming
back tow2, etc.
oMust keep track of vertices already visited to avoid cycles.
oThe method can be implemented using recursion or iteration.
oThe iterative preorder depth-first algorithm is:
push the starting vertex onto the stack
while(stack is not empty){
pop a vertex off the stack, call it v
if v is not already visited, visit it
push vertices adjacent to v, not visited, onto the stackt
}