SlideShare a Scribd company logo
GRAPHS
DATA STRUCTURES
MUHAMMAD HAMMAD WASEEM
1
WHAT IS A GRAPH?
• A data structure that consists of a set of
nodes (vertices) and a set of edges that relate
the nodes to each other
• The set of edges describes relationships
among the vertices
2
FORMAL DEFINITION OF GRAPHS
• A graph G is defined as follows:
G=(V,E)
V(G): a finite, nonempty set of vertices
E(G): a set of edges (pairs of vertices)
3
DIRECTED VS. UNDIRECTED
GRAPHS
• When the edges in a graph have no direction, the
graph is called undirected.
• When the edges in a graph have a direction, the
graph is called directed (or digraph)
4
E(Graph2) = {(1,3) (3,1) (5,9) (9,11)
TREES VS. GRAPHS
• Trees are special cases of graphs!!
5
GRAPH TERMINOLOGY
• Adjacent nodes: two nodes are adjacent if they are connected
by an edge
• Path: a sequence of vertices that connect two nodes in a graph
• Complete graph: a graph in which every vertex is directly
connected to every other vertex
• Degree of a vertex: The degree of a vertex in a graph is the
number of edges that touch it.
• The Size of a Graph: The size of a graph is the number of
vertices that it has.
6
5 is adjacent to 7
7 is adjacent from 5
GRAPH TERMINOLOGY
(CONT.)
• What is the number of edges in a
complete directed graph with N
vertices?
N * (N-1)
7
2
( )O N
GRAPH TERMINOLOGY
(CONT.)
• What is the number of edges in a
complete undirected graph with N
vertices?
N * (N-1) / 2
8
2
( )O N
GRAPH TERMINOLOGY
(CONT.)
• Weighted graph: a graph in which each
edge carries a value
9
GRAPH IMPLEMENTATION
• Array-based implementation
• A 1D array is used to represent the vertices
• A 2D array (adjacency matrix) is used to represent
the edges
10
ARRAY-BASED IMPLEMENTATION
11
GRAPH IMPLEMENTATION
(CONT.)
• Linked-list implementation
• A 1D array is used to represent the
vertices
• A list is used for each vertex v which
contains the vertices which are adjacent
from v (adjacency list)
12
LINKED-LIST IMPLEMENTATION
13
ADJACENCY MATRIX VS.
ADJACENCY LIST
REPRESENTATION
• Adjacency matrix
• Good for dense graphs --|E|~O(|V|2)
• Memory requirements: O(|V| + |E| ) = O(|V|2 )
• Connectivity between two vertices can be tested quickly
• Adjacency list
• Good for sparse graphs -- |E|~O(|V|)
• Memory requirements: O(|V| + |E|)=O(|V|)
• Vertices adjacent to another vertex can be found quickly
14
GRAPH SEARCHING
• Problem: find a path between two nodes of the
graph (e.g., Austin and Washington)
• Methods: Depth-First-Search (DFS) or Breadth-
First-Search (BFS)
15
DEPTH-FIRST-SEARCH (DFS)
• What is the idea behind DFS?
• Travel as far as you can down a path
• Back up as little as possible when you reach a "dead
end" (i.e., next vertex has been "marked" or there is
no next vertex)
• DFS can be implemented efficiently using a
stack
16
DEPTH-FIRST-SEARCH (DFS)
(CONT.)Set found to false
stack.Push(startVertex)
DO
stack.Pop(vertex)
IF vertex == endVertex
Set found to true
ELSE
Push all adjacent vertices onto stack
WHILE !stack.IsEmpty() AND !found
IF(!found)
Write "Path does not exist"
17
start end
(initialization)
18
19
20
BREADTH-FIRST-SEARCHING
(BFS)
• What is the idea behind BFS?
• Look at all possible paths at the same depth before
you go at a deeper level
• Back up as far as possible when you reach a "dead
end" (i.e., next vertex has been "marked" or there is
no next vertex)
21
BREADTH-FIRST-SEARCHING (BFS)
(CONT.)
• BFS can be implemented efficiently using
a queue
Set found to false
queue.Enqueue(startVertex)
DO
queue.Dequeue(vertex)
IF vertex == endVertex
Set found to true
ELSE
Enqueue all adjacent vertices onto queue
WHILE !queue.IsEmpty() AND !found
• Should we mark a vertex when it is
enqueued or when it is dequeued ? 22
IF(!found)
Write "Path does not exist"
start end
(initialization)
23
next:
24
25
SINGLE-SOURCE SHORTEST-
PATH PROBLEM
• There are multiple paths from a source vertex
to a destination vertex
• Shortest path: the path whose total weight
(i.e., sum of edge weights) is minimum
• Examples:
• Austin->Houston->Atlanta->Washington: 1560
miles
• Austin->Dallas->Denver->Atlanta->Washington:
2980 miles
26
SINGLE-SOURCE SHORTEST-
PATH PROBLEM (CONT.)
• Common algorithms: Dijkstra's algorithm,
Bellman-Ford algorithm
• BFS can be used to solve the shortest graph
problem when the graph is weightless or all
the weights are the same
(mark vertices before Enqueue)
27
SIMPLE SEARCH
ALGORITHM
Let S be the start state
1. Initialize Q with the start node Q=(S) as
only entry; set Visited = (S)
2. If Q is empty, fail. Else pick node X from
Q
3. If X is a goal, return X, we’ve reached the
goal
4. (Otherwise) Remove X from Q
5. Find all the children of node X not in
Visited
6. Add these to Q; Add Children of X to
Visited
7. Go to Step 2
28
DEPTH FIRST SEARCH(DFS)
• Expand deepest unexpanded node
• Implementation:
• fringe = LIFO queue, i.e., put successors at front
• Properties of DFS
• Complete: No, fails in infinite-depth spaces, spaces with
loops
• Modify to avoid repeated states along path
• Complete in finite spaces
• Time: O(bm): terrible if m is much larger than d
• but if solutions are dense, may be much faster than
breadth-first
• Space: O(bm), i.e., linear space!
29
DFS: EXAMPLE
Q Visited
1
2
3
4
5
30
S
BA
E FDC
G H
DFS: EXAMPLE
Q Visited
1 S S
2
3
4
5
31
S
BA
E FDC
G H
DFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3
4
5
32
S
BA
E FDC
G H
DFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 C,D,B S,A,B,C,D
4
5
33
S
BA
E FDC
G H
DFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 C,D,B S,A,B,C,D
4 G,H,D,B S,A,B,C,D,G,H
5
34
S
BA
E FDC
G H
DFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 C,D,B S,A,B,C,D
4 G,H,D,B S,A,B,C,D,G,H
5 H,D,B S,A,B,C,D,G,H
35
S
BA
E FDC
G H
DFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 C,D,B S,A,B,C,D
4 G,H,D,B S,A,B,C,D,G,H
5 H,D,B S,A,B,C,D,G,H
6 D,B S,A,B,C,D,G,H
36
S
BA
E FDC
G H
DFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 C,D,B S,A,B,C,D
4 G,H,D,B S,A,B,C,D,G,H
5 H,D,B S,A,B,C,D,G,H
6 D,B S,A,B,C,D,G,H
37
S
BA
E FDC
G H
BREADTH FIRST SEARCH(BFS)
• Expand shallowest unexpanded node
• Implementation:
• fringe = FIFO queue, i.e., New successors go at end
• Properties of DFS
• Complete: Yes(if b is finite)
• Time: 1+b+b2+b3+… +bd + b(bd-1) = O(bd+1)
• Space: O(bd+1) (keeps every node in memory)
• Imagine searching a tree with branching factor 8 and depth 10.
Assume a node requires just 8 bytes of storage. The breadth first
search might require up to:
= (8)10 nodes
= (23)10 X 23 = 233 bytes
= 8,000 Mbytes
= 8 Gbytes
• Optimal: Yes (if cost = 1 per step)
38
BFS: EXAMPLE
Q Visited
1
2
3
4
5
39
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
1 S S
2
3
4
5
40
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3
4
5
41
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 B,C,D S,A,B,C,D
4
5
42
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 B,C,D S,A,B,C,D
4
5
43
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 B,C,D S,A,B,C,D
4 C,D,E,F S,A,B,C,D,E,F
5
44
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
2 A,B S,A,B
3 B,C,D S,A,B,C,D
4 C,D,E,F S,A,B,C,D,E,F
5 D,E,F,G,H S,A,B,C,D,E,F,G,H
6
45
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
3 B,C,D S,A,B,C,D
4 C,D,E,F S,A,B,C,D,E,F
5 D,E,F,G,H S,A,B,C,D,E,F,G,H
6 E,F,G,H S,A,B,C,D,E,F,G,H
7
46
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
4 C,D,E,F S,A,B,C,D,E,F
5 D,E,F,G,H S,A,B,C,D,E,F,G,H
6 E,F,G,H S,A,B,C,D,E,F,G,H
7 F,G,H S,A,B,C,D,E,F,G,H
8
47
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
5 D,E,F,G,H S,A,B,C,D,E,F,G,H
6 E,F,G,H S,A,B,C,D,E,F,G,H
7 F,G,H S,A,B,C,D,E,F,G,H
8 G,H S,A,B,C,D,E,F,G,H
9
48
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
6 E,F,G,H S,A,B,C,D,E,F,G,H
7 F,G,H S,A,B,C,D,E,F,G,H
8 G,H S,A,B,C,D,E,F,G,H
9 H S,A,B,C,D,E,F,G,H
10
49
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
6 E,F,G,H S,A,B,C,D,E,F,G,H
7 F,G,H S,A,B,C,D,E,F,G,H
8 G,H S,A,B,C,D,E,F,G,H
9 S,A,B,C,D,E,F,G,H
10 S,A,B,C,D,E,F,G,H
50
S
BA
E FDC
G H
BFS: EXAMPLE
Q Visited
1 S S
2 A,B S,A,B
3 B,C,D S,A,B,C,D
4 C,D,E,F S,A,B,C,D,E,F
5 D,E,F,G,H S,A,B,C,D,E,F,G,H
6 E,F,G,H S,A,B,C,D,E,F,G,H
7 F,G,H S,A,B,C,D,E,F,G,H
8 G,H S,A,B,C,D,E,F,G,H
9 H S,A,B,C,D,E,F,G,H
10 S,A,B,C,D,E,F,G,H
51
S
BA
E FDC
G H
THANKS
• Implement DFS and BFS in lab and submit
softcopy at m.hammad.wasim@gmail.com
52
Ad

Recommended

Data structure - Graph
Data structure - Graph
Madhu Bala
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
Siddhi Shrivas
 
Graph representation
Graph representation
Tech_MX
 
Trees (data structure)
Trees (data structure)
Trupti Agrawal
 
Skip list vinay khimsuriya_200430723005
Skip list vinay khimsuriya_200430723005
vinaykhimsuriya1
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
Graph data structure and algorithms
Graph data structure and algorithms
Anandhasilambarasan D
 
DFS and BFS
DFS and BFS
satya parsana
 
Tree Traversal
Tree Traversal
Md. Israil Fakir
 
Dijkstra's Algorithm
Dijkstra's Algorithm
ArijitDhali
 
Bellman Ford's Algorithm
Bellman Ford's Algorithm
Tanmay Baranwal
 
Depth-First Search
Depth-First Search
Dakshitha Dissanayaka
 
Graph in data structure
Graph in data structure
Abrish06
 
Binary Tree in Data Structure
Binary Tree in Data Structure
Meghaj Mallick
 
SINGLE-SOURCE SHORTEST PATHS
SINGLE-SOURCE SHORTEST PATHS
Md. Shafiuzzaman Hira
 
Binary search tree(bst)
Binary search tree(bst)
Hossain Md Shakhawat
 
Singly linked list
Singly linked list
Amar Jukuntla
 
sparse matrix in data structure
sparse matrix in data structure
MAHALAKSHMI P
 
Insertion Sort Algorithm
Insertion Sort Algorithm
Gail Carmichael
 
Functional dependencies and normalization
Functional dependencies and normalization
daxesh chauhan
 
Hashing Technique In Data Structures
Hashing Technique In Data Structures
SHAKOOR AB
 
Depth first search [dfs]
Depth first search [dfs]
DEEPIKA T
 
Insertion sort
Insertion sort
almaqboli
 
Tree in data structure
Tree in data structure
ghhgj jhgh
 
Insertion sort
Insertion sort
Monalisa Patel
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queue
Srajan Shukla
 
Linked lists
Linked lists
SARITHA REDDY
 
Threaded Binary Tree.pptx
Threaded Binary Tree.pptx
pavankumarjakkepalli
 
Graphs In Data Structure
Graphs In Data Structure
Anuj Modi
 
Lecture8 data structure(graph)
Lecture8 data structure(graph)
Taibah University, College of Computer Science & Engineering
 

More Related Content

What's hot (20)

Tree Traversal
Tree Traversal
Md. Israil Fakir
 
Dijkstra's Algorithm
Dijkstra's Algorithm
ArijitDhali
 
Bellman Ford's Algorithm
Bellman Ford's Algorithm
Tanmay Baranwal
 
Depth-First Search
Depth-First Search
Dakshitha Dissanayaka
 
Graph in data structure
Graph in data structure
Abrish06
 
Binary Tree in Data Structure
Binary Tree in Data Structure
Meghaj Mallick
 
SINGLE-SOURCE SHORTEST PATHS
SINGLE-SOURCE SHORTEST PATHS
Md. Shafiuzzaman Hira
 
Binary search tree(bst)
Binary search tree(bst)
Hossain Md Shakhawat
 
Singly linked list
Singly linked list
Amar Jukuntla
 
sparse matrix in data structure
sparse matrix in data structure
MAHALAKSHMI P
 
Insertion Sort Algorithm
Insertion Sort Algorithm
Gail Carmichael
 
Functional dependencies and normalization
Functional dependencies and normalization
daxesh chauhan
 
Hashing Technique In Data Structures
Hashing Technique In Data Structures
SHAKOOR AB
 
Depth first search [dfs]
Depth first search [dfs]
DEEPIKA T
 
Insertion sort
Insertion sort
almaqboli
 
Tree in data structure
Tree in data structure
ghhgj jhgh
 
Insertion sort
Insertion sort
Monalisa Patel
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queue
Srajan Shukla
 
Linked lists
Linked lists
SARITHA REDDY
 
Threaded Binary Tree.pptx
Threaded Binary Tree.pptx
pavankumarjakkepalli
 
Dijkstra's Algorithm
Dijkstra's Algorithm
ArijitDhali
 
Bellman Ford's Algorithm
Bellman Ford's Algorithm
Tanmay Baranwal
 
Graph in data structure
Graph in data structure
Abrish06
 
Binary Tree in Data Structure
Binary Tree in Data Structure
Meghaj Mallick
 
sparse matrix in data structure
sparse matrix in data structure
MAHALAKSHMI P
 
Insertion Sort Algorithm
Insertion Sort Algorithm
Gail Carmichael
 
Functional dependencies and normalization
Functional dependencies and normalization
daxesh chauhan
 
Hashing Technique In Data Structures
Hashing Technique In Data Structures
SHAKOOR AB
 
Depth first search [dfs]
Depth first search [dfs]
DEEPIKA T
 
Insertion sort
Insertion sort
almaqboli
 
Tree in data structure
Tree in data structure
ghhgj jhgh
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queue
Srajan Shukla
 

Viewers also liked (20)

Graphs In Data Structure
Graphs In Data Structure
Anuj Modi
 
Lecture8 data structure(graph)
Lecture8 data structure(graph)
Taibah University, College of Computer Science & Engineering
 
Data structure computer graphs
Data structure computer graphs
Kumar
 
Graph data structure
Graph data structure
Tech_MX
 
Matrix Representation Of Graph
Matrix Representation Of Graph
Abhishek Pachisia
 
Graphs in data structure
Graphs in data structure
hamza javed
 
17. Trees and Graphs
17. Trees and Graphs
Intro C# Book
 
DATA STRUCTURES
DATA STRUCTURES
bca2010
 
Graphs in Data Structure
Graphs in Data Structure
hafsa komal
 
Graphs data Structure
Graphs data Structure
Mahmoud Alfarra
 
Data structure & its types
Data structure & its types
Rameesha Sadaqat
 
Graph Basic In Data structure
Graph Basic In Data structure
Ikhlas Rahman
 
Data structure and its types
Data structure and its types
Navtar Sidhu Brar
 
Trees data structure
Trees data structure
Sumit Gupta
 
Depth First Search and Breadth First Search
Depth First Search and Breadth First Search
Benjamin Sach
 
Preparation Data Structures 11 graphs
Preparation Data Structures 11 graphs
Andres Mendez-Vazquez
 
Data Structures, Graphs
Data Structures, Graphs
Jibrael Jos
 
Graphss
Graphss
fika sweety
 
Data structure introduction
Data structure introduction
ramyasanthosh
 
Graphs in data structures
Graphs in data structures
Savit Chandra
 
Graphs In Data Structure
Graphs In Data Structure
Anuj Modi
 
Data structure computer graphs
Data structure computer graphs
Kumar
 
Graph data structure
Graph data structure
Tech_MX
 
Matrix Representation Of Graph
Matrix Representation Of Graph
Abhishek Pachisia
 
Graphs in data structure
Graphs in data structure
hamza javed
 
17. Trees and Graphs
17. Trees and Graphs
Intro C# Book
 
DATA STRUCTURES
DATA STRUCTURES
bca2010
 
Graphs in Data Structure
Graphs in Data Structure
hafsa komal
 
Data structure & its types
Data structure & its types
Rameesha Sadaqat
 
Graph Basic In Data structure
Graph Basic In Data structure
Ikhlas Rahman
 
Data structure and its types
Data structure and its types
Navtar Sidhu Brar
 
Trees data structure
Trees data structure
Sumit Gupta
 
Depth First Search and Breadth First Search
Depth First Search and Breadth First Search
Benjamin Sach
 
Preparation Data Structures 11 graphs
Preparation Data Structures 11 graphs
Andres Mendez-Vazquez
 
Data Structures, Graphs
Data Structures, Graphs
Jibrael Jos
 
Data structure introduction
Data structure introduction
ramyasanthosh
 
Graphs in data structures
Graphs in data structures
Savit Chandra
 
Ad

Similar to Data Structures - Lecture 10 [Graphs] (20)

Unit 9 graph
Unit 9 graph
Dabbal Singh Mahara
 
LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
MuhammadUmerIhtisham
 
Unit ix graph
Unit ix graph
Tribhuvan University
 
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
chandrashekarr799
 
22-graphs1-dfs-bfs.ppt data structures ppt
22-graphs1-dfs-bfs.ppt data structures ppt
SyedAliShahid3
 
22-graphs1-dfs-bfs.ppt
22-graphs1-dfs-bfs.ppt
KarunaBiswas3
 
U1 L5 DAA.pdf
U1 L5 DAA.pdf
LakshyaBaliyan2
 
Graph Data Structure
Graph Data Structure
Afaq Mansoor Khan
 
Breadth first search
Breadth first search
Sazzad Hossain
 
Unit-6 Graph.ppsx ppt
Unit-6 Graph.ppsx ppt
DhruvilSTATUS
 
Data Structures-Non Linear DataStructures-Graphs
Data Structures-Non Linear DataStructures-Graphs
sailaja156145
 
Graphhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.pdf
Graphhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.pdf
timoemin50
 
lecture 17
lecture 17
sajinsc
 
Graphs
Graphs
Dwight Sabio
 
Graphs
Graphs
LavanyaJ28
 
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
whittemorelucilla
 
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
abdulrafaychaudhry
 
Design and analysis of Algorithms Lecture 1 (BFS, DFS).ppsx
Design and analysis of Algorithms Lecture 1 (BFS, DFS).ppsx
SababAshfakFahim
 
Unit 2: All
Unit 2: All
Hector Zenil
 
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
pournima055
 
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
chandrashekarr799
 
22-graphs1-dfs-bfs.ppt data structures ppt
22-graphs1-dfs-bfs.ppt data structures ppt
SyedAliShahid3
 
22-graphs1-dfs-bfs.ppt
22-graphs1-dfs-bfs.ppt
KarunaBiswas3
 
Unit-6 Graph.ppsx ppt
Unit-6 Graph.ppsx ppt
DhruvilSTATUS
 
Data Structures-Non Linear DataStructures-Graphs
Data Structures-Non Linear DataStructures-Graphs
sailaja156145
 
Graphhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.pdf
Graphhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.pdf
timoemin50
 
lecture 17
lecture 17
sajinsc
 
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
whittemorelucilla
 
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
abdulrafaychaudhry
 
Design and analysis of Algorithms Lecture 1 (BFS, DFS).ppsx
Design and analysis of Algorithms Lecture 1 (BFS, DFS).ppsx
SababAshfakFahim
 
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
pournima055
 
Ad

More from Muhammad Hammad Waseem (20)

[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
[ITP - Lecture 14] Recursion
[ITP - Lecture 14] Recursion
Muhammad Hammad Waseem
 
[ITP - Lecture 13] Introduction to Pointers
[ITP - Lecture 13] Introduction to Pointers
Muhammad Hammad Waseem
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
Muhammad Hammad Waseem
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
Muhammad Hammad Waseem
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
Muhammad Hammad Waseem
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Muhammad Hammad Waseem
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 13] Introduction to Pointers
[ITP - Lecture 13] Introduction to Pointers
Muhammad Hammad Waseem
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
Muhammad Hammad Waseem
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
Muhammad Hammad Waseem
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
Muhammad Hammad Waseem
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Muhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 

Recently uploaded (20)

IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
How to use search fetch method in Odoo 18
How to use search fetch method in Odoo 18
Celine George
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
How to use search fetch method in Odoo 18
How to use search fetch method in Odoo 18
Celine George
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 

Data Structures - Lecture 10 [Graphs]

  • 2. WHAT IS A GRAPH? • A data structure that consists of a set of nodes (vertices) and a set of edges that relate the nodes to each other • The set of edges describes relationships among the vertices 2
  • 3. FORMAL DEFINITION OF GRAPHS • A graph G is defined as follows: G=(V,E) V(G): a finite, nonempty set of vertices E(G): a set of edges (pairs of vertices) 3
  • 4. DIRECTED VS. UNDIRECTED GRAPHS • When the edges in a graph have no direction, the graph is called undirected. • When the edges in a graph have a direction, the graph is called directed (or digraph) 4 E(Graph2) = {(1,3) (3,1) (5,9) (9,11)
  • 5. TREES VS. GRAPHS • Trees are special cases of graphs!! 5
  • 6. GRAPH TERMINOLOGY • Adjacent nodes: two nodes are adjacent if they are connected by an edge • Path: a sequence of vertices that connect two nodes in a graph • Complete graph: a graph in which every vertex is directly connected to every other vertex • Degree of a vertex: The degree of a vertex in a graph is the number of edges that touch it. • The Size of a Graph: The size of a graph is the number of vertices that it has. 6 5 is adjacent to 7 7 is adjacent from 5
  • 7. GRAPH TERMINOLOGY (CONT.) • What is the number of edges in a complete directed graph with N vertices? N * (N-1) 7 2 ( )O N
  • 8. GRAPH TERMINOLOGY (CONT.) • What is the number of edges in a complete undirected graph with N vertices? N * (N-1) / 2 8 2 ( )O N
  • 9. GRAPH TERMINOLOGY (CONT.) • Weighted graph: a graph in which each edge carries a value 9
  • 10. GRAPH IMPLEMENTATION • Array-based implementation • A 1D array is used to represent the vertices • A 2D array (adjacency matrix) is used to represent the edges 10
  • 12. GRAPH IMPLEMENTATION (CONT.) • Linked-list implementation • A 1D array is used to represent the vertices • A list is used for each vertex v which contains the vertices which are adjacent from v (adjacency list) 12
  • 14. ADJACENCY MATRIX VS. ADJACENCY LIST REPRESENTATION • Adjacency matrix • Good for dense graphs --|E|~O(|V|2) • Memory requirements: O(|V| + |E| ) = O(|V|2 ) • Connectivity between two vertices can be tested quickly • Adjacency list • Good for sparse graphs -- |E|~O(|V|) • Memory requirements: O(|V| + |E|)=O(|V|) • Vertices adjacent to another vertex can be found quickly 14
  • 15. GRAPH SEARCHING • Problem: find a path between two nodes of the graph (e.g., Austin and Washington) • Methods: Depth-First-Search (DFS) or Breadth- First-Search (BFS) 15
  • 16. DEPTH-FIRST-SEARCH (DFS) • What is the idea behind DFS? • Travel as far as you can down a path • Back up as little as possible when you reach a "dead end" (i.e., next vertex has been "marked" or there is no next vertex) • DFS can be implemented efficiently using a stack 16
  • 17. DEPTH-FIRST-SEARCH (DFS) (CONT.)Set found to false stack.Push(startVertex) DO stack.Pop(vertex) IF vertex == endVertex Set found to true ELSE Push all adjacent vertices onto stack WHILE !stack.IsEmpty() AND !found IF(!found) Write "Path does not exist" 17
  • 19. 19
  • 20. 20
  • 21. BREADTH-FIRST-SEARCHING (BFS) • What is the idea behind BFS? • Look at all possible paths at the same depth before you go at a deeper level • Back up as far as possible when you reach a "dead end" (i.e., next vertex has been "marked" or there is no next vertex) 21
  • 22. BREADTH-FIRST-SEARCHING (BFS) (CONT.) • BFS can be implemented efficiently using a queue Set found to false queue.Enqueue(startVertex) DO queue.Dequeue(vertex) IF vertex == endVertex Set found to true ELSE Enqueue all adjacent vertices onto queue WHILE !queue.IsEmpty() AND !found • Should we mark a vertex when it is enqueued or when it is dequeued ? 22 IF(!found) Write "Path does not exist"
  • 25. 25
  • 26. SINGLE-SOURCE SHORTEST- PATH PROBLEM • There are multiple paths from a source vertex to a destination vertex • Shortest path: the path whose total weight (i.e., sum of edge weights) is minimum • Examples: • Austin->Houston->Atlanta->Washington: 1560 miles • Austin->Dallas->Denver->Atlanta->Washington: 2980 miles 26
  • 27. SINGLE-SOURCE SHORTEST- PATH PROBLEM (CONT.) • Common algorithms: Dijkstra's algorithm, Bellman-Ford algorithm • BFS can be used to solve the shortest graph problem when the graph is weightless or all the weights are the same (mark vertices before Enqueue) 27
  • 28. SIMPLE SEARCH ALGORITHM Let S be the start state 1. Initialize Q with the start node Q=(S) as only entry; set Visited = (S) 2. If Q is empty, fail. Else pick node X from Q 3. If X is a goal, return X, we’ve reached the goal 4. (Otherwise) Remove X from Q 5. Find all the children of node X not in Visited 6. Add these to Q; Add Children of X to Visited 7. Go to Step 2 28
  • 29. DEPTH FIRST SEARCH(DFS) • Expand deepest unexpanded node • Implementation: • fringe = LIFO queue, i.e., put successors at front • Properties of DFS • Complete: No, fails in infinite-depth spaces, spaces with loops • Modify to avoid repeated states along path • Complete in finite spaces • Time: O(bm): terrible if m is much larger than d • but if solutions are dense, may be much faster than breadth-first • Space: O(bm), i.e., linear space! 29
  • 31. DFS: EXAMPLE Q Visited 1 S S 2 3 4 5 31 S BA E FDC G H
  • 32. DFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 4 5 32 S BA E FDC G H
  • 33. DFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 C,D,B S,A,B,C,D 4 5 33 S BA E FDC G H
  • 34. DFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 C,D,B S,A,B,C,D 4 G,H,D,B S,A,B,C,D,G,H 5 34 S BA E FDC G H
  • 35. DFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 C,D,B S,A,B,C,D 4 G,H,D,B S,A,B,C,D,G,H 5 H,D,B S,A,B,C,D,G,H 35 S BA E FDC G H
  • 36. DFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 C,D,B S,A,B,C,D 4 G,H,D,B S,A,B,C,D,G,H 5 H,D,B S,A,B,C,D,G,H 6 D,B S,A,B,C,D,G,H 36 S BA E FDC G H
  • 37. DFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 C,D,B S,A,B,C,D 4 G,H,D,B S,A,B,C,D,G,H 5 H,D,B S,A,B,C,D,G,H 6 D,B S,A,B,C,D,G,H 37 S BA E FDC G H
  • 38. BREADTH FIRST SEARCH(BFS) • Expand shallowest unexpanded node • Implementation: • fringe = FIFO queue, i.e., New successors go at end • Properties of DFS • Complete: Yes(if b is finite) • Time: 1+b+b2+b3+… +bd + b(bd-1) = O(bd+1) • Space: O(bd+1) (keeps every node in memory) • Imagine searching a tree with branching factor 8 and depth 10. Assume a node requires just 8 bytes of storage. The breadth first search might require up to: = (8)10 nodes = (23)10 X 23 = 233 bytes = 8,000 Mbytes = 8 Gbytes • Optimal: Yes (if cost = 1 per step) 38
  • 40. BFS: EXAMPLE Q Visited 1 S S 2 3 4 5 40 S BA E FDC G H
  • 41. BFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 4 5 41 S BA E FDC G H
  • 42. BFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 B,C,D S,A,B,C,D 4 5 42 S BA E FDC G H
  • 43. BFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 B,C,D S,A,B,C,D 4 5 43 S BA E FDC G H
  • 44. BFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 B,C,D S,A,B,C,D 4 C,D,E,F S,A,B,C,D,E,F 5 44 S BA E FDC G H
  • 45. BFS: EXAMPLE Q Visited 2 A,B S,A,B 3 B,C,D S,A,B,C,D 4 C,D,E,F S,A,B,C,D,E,F 5 D,E,F,G,H S,A,B,C,D,E,F,G,H 6 45 S BA E FDC G H
  • 46. BFS: EXAMPLE Q Visited 3 B,C,D S,A,B,C,D 4 C,D,E,F S,A,B,C,D,E,F 5 D,E,F,G,H S,A,B,C,D,E,F,G,H 6 E,F,G,H S,A,B,C,D,E,F,G,H 7 46 S BA E FDC G H
  • 47. BFS: EXAMPLE Q Visited 4 C,D,E,F S,A,B,C,D,E,F 5 D,E,F,G,H S,A,B,C,D,E,F,G,H 6 E,F,G,H S,A,B,C,D,E,F,G,H 7 F,G,H S,A,B,C,D,E,F,G,H 8 47 S BA E FDC G H
  • 48. BFS: EXAMPLE Q Visited 5 D,E,F,G,H S,A,B,C,D,E,F,G,H 6 E,F,G,H S,A,B,C,D,E,F,G,H 7 F,G,H S,A,B,C,D,E,F,G,H 8 G,H S,A,B,C,D,E,F,G,H 9 48 S BA E FDC G H
  • 49. BFS: EXAMPLE Q Visited 6 E,F,G,H S,A,B,C,D,E,F,G,H 7 F,G,H S,A,B,C,D,E,F,G,H 8 G,H S,A,B,C,D,E,F,G,H 9 H S,A,B,C,D,E,F,G,H 10 49 S BA E FDC G H
  • 50. BFS: EXAMPLE Q Visited 6 E,F,G,H S,A,B,C,D,E,F,G,H 7 F,G,H S,A,B,C,D,E,F,G,H 8 G,H S,A,B,C,D,E,F,G,H 9 S,A,B,C,D,E,F,G,H 10 S,A,B,C,D,E,F,G,H 50 S BA E FDC G H
  • 51. BFS: EXAMPLE Q Visited 1 S S 2 A,B S,A,B 3 B,C,D S,A,B,C,D 4 C,D,E,F S,A,B,C,D,E,F 5 D,E,F,G,H S,A,B,C,D,E,F,G,H 6 E,F,G,H S,A,B,C,D,E,F,G,H 7 F,G,H S,A,B,C,D,E,F,G,H 8 G,H S,A,B,C,D,E,F,G,H 9 H S,A,B,C,D,E,F,G,H 10 S,A,B,C,D,E,F,G,H 51 S BA E FDC G H
  • 52. THANKS • Implement DFS and BFS in lab and submit softcopy at [email protected] 52