DS-Lec14(Graph Data Structure)
DS-Lec14(Graph Data Structure)
Topic Name
INTRODUCTION OF GRAPH DATA STRUCTURE
Instructor:
Zainab Malik
2
Content
• Introduction to Graph Data Structure
adjacency list.
• Graph Traversal (Breadth-First Search and depth First Search)
3
Applications Of Graph
• Google Maps, Apple Maps, Waze use graphs to treat all cities and
places as nodes and routes between them as edges.
• Uber, Ola, Lyft uses a graph to find the shortest and cheapest path for a
car from one city to another.
Types of graphs
• Undirected Graphs
• Directed Graphs
7
Undirected Graph:
In an undirected graph, nodes are connected by edges that are
all bidirectional. For example if an edge connects node 1 and 2,
we can traverse from node 1 to node 2, and from node 2 to 1.
8
Directed Graph
• In a directed graph, nodes are connected by directed edges –
they only go in one direction. For example, if an edge connects
node 1 and 2, but the arrow head points towards 2, we can
only traverse from node 1 to node 2 – not in the opposite
direction.
9
Graph Representations
• Graph data structure is represented using following
representations.
1. Adjacency Matrix
2. Adjacency List
10
Adjacency List
• To create an Adjacency list, an array of lists is used. The size of
the array is equal to the number of nodes.
• A single index, array[i] represents the list of nodes adjacent to
the ith node.
12
Example:
Tree is a type of a graph.
For practice create its Adjacency Matrix and Adjacency List
13
Example
• In this Example we are discussing about the Depth First
Search(DFS) Algorithm Step by Step.
• In the Depth First Search(DFS) algorithm we are using a Stack
Data Structure.
Step 1:
• Step 2:
Display: S
Step 3:
• Step 4:
Visit D and mark it as visited and put
onto the stack. Here, we
have B and C nodes, which are
adjacent to D and both are unvisited.
However, we shall again choose in an
alphabetical order.
Step 5: Display: S, A, D
• Step 6:
Display: S, A, D, B
Step 7:
Only unvisited adjacent node is
from D is C now. So we visit C, mark it
as visited and put it onto the stack.
Display: S, A, D, B, C
18
• Step 8:
• As C does not have any unvisited adjacent node so we
keep popping the stack until we find a node that has an
unvisited adjacent node. In this case, there's none and we
keep popping until the stack is empty.
Display: S, A, D, B, C
19
Example
• In this Example we are discussing about the Breadth First Search
(BFS) Algorithm Step by Step.
• In the Breadth First Search (BFS) algorithm we are using a Queue
Data Structure.
• Step 01:
• Step 02:
Display: S
Step 03:
We then see an unvisited adjacent
node from S. In this example, we have
three nodes but alphabetically we
choose A, mark it as visited and
enqueue it.
Display: S, A
22
• Step 04:
Display: S, A, B
Step 05:
Display: S, A, B, C
23
• Step 06:
Display: S, A, B, C
Step 07:
Display: S, A, B, C, D
24
Display: S, A, B, C, D
25
Thank You