Uploaded by manasishitole96

Graph

advertisement
Graph
Definition
Graph is a data structure that consists of
following two components:
 A finite set of vertices also called as nodes.
 A finite set of ordered pair of the form (u, v)
called as edge.
 The pair is ordered because (u, v) is not same
as (v, u) in case of a directed graph(di-graph).
 The pair of the form (u, v) indicates that there
is an edge from vertex u to vertex v.
 The edges may contain weight/value/cost.
Example
Directed Graph- A directed graph is a set
of vertices (nodes) connected by edges, with
each node having a direction associated with
it.
Edges are usually represented by arrows
pointing in the direction the graph can be
traversed.
Undirected Graph- In an undirected
graph the edges don’t have direction
associated with them. Hence, the graph can be
traversed in either direction. The absence of
an arrow tells us that the graph is undirected.
Graph Representation
Adjacency Matrix:
Adjacency Matrix is a 2D array of size V x V
where V is the number of vertices in a
graph.
Let the 2D array be A[][], where
A[i][j] = 1 indicates that there is an edge
from vertex i to vertex j. Adjacency matrix
for undirected graph is always symmetric.
Example
Graph Representation
Adjacency List
An array of lists is used.
Size of the array is equal to the number of
vertices.
Let the array be A[].
An entry A[i] represents the list of vertices
adjacent to the ith vertex.

Example
Graph Traversal
Breadth First Search (BFS)
 Step 1: Insert the root node in the Queue.
 Step 2: Loop until the queue is empty.
 Step 3: Remove the node from the Queue.
 Step 4: If the removed node has unvisited
adjacent nodes, mark them as visited and insert
the unvisited adjacent nodes in the queue.
Example
BFS: A, B, C, D, E, F
Graph Traversal
Depth First Search (BFS)
 Step 1: Push the root node in the Stack.
 Step 2: Loop until stack is empty.
 Step 3: Pop the node of the stack.
 Step 4: If the node has unvisited adjacent nodes,
get the unvisited adjacent node, mark it as
traversed and push it on stack.
 Step 5: If the node does not have any unvisited
child nodes, pop the node from the stack.
Example
DFS: A, B, E, F, C, D
Download