Professional Documents
Culture Documents
Graphs-LectureSlides Converted by Abcdpdf
Graphs-LectureSlides Converted by Abcdpdf
Advanced Algorithms
Advanced Algorithms
Graph Terminology
• A graph is an ordered pair G=(V,E) with a set of
vertices or nodes and the edges that connect them
7
Data Structures for Graphs
An Adjacency Matrix
• For an undirected graph, the matrix will be
symmetric along the diagonal
8
Adjacency Matrix
• |V| |V| matrix A.
• Number vertices from 1 to |V| in some arbitrary
manner.
1 2
a b 1 2 3 4
1 0 1 1 1
2 0 0 1 0 1 if (i, j ) E
A[i, j ] aij
c d4 3 0 0 0 1 0 otherwise
3 4 0 0 0 0
1 2 1 2 3 4
a b
1 0 1 1 1
A = AT for undirected graphs.
2 1 0 1 0
c d 3 1 1 0 1
3 4 4 1 0 1 0
Space and Time
• Space: (V2).
– Not memory efficient for large graphs.
• Time: to list all vertices adjacent to u: (V).
• Time: to determine if (u, v) E: (1).
• Can store weights instead of bits for weighted graph.
Adjacency Matrix Example 1
11
Adjacency Matrix Example 2
12
Data Structures for Graphs
An Adjacency List
13
Adjacency List Example 1
14
Adjacency List Example 2
15
Breadth-First Traversal
• From the starting node, follow all paths of
length one
16
Breadth-First Traversal Example
17
Depth-First Traversal
• Follow a path through the graph until it reaches
a dead end
18
Depth-First Traversal Example
• Consider the following graph:
19
Data Structures use in DFS
a b e
b d c
V a d
Graph with 5 Vertices
F b a c e
U c d b e
F d a e c TOS
b
U e b d c d
G D C
destination
A B D C D
Initial call to BFS on A Dequeue A Dequeue B Dequeue C
Add A to queue Add B Add C, D Nothing to add
rear front
• DFS & BFS give rise to spanning trees, but they don’t consider
weights.
Kruskal’s Algorithm
• An algorithm to find the minimum spanning tree of connected
graph.
Step 1: Initially all the edges of the graph are sorted based on
their weights.
Step2: Select the edge with minimum weight from the sorted list
in step 1.Selected edge shouldn’t form a cycle. Selected edge
is added into the tree or forest.
Step 3: Repeat step 2 till the tree contains all nodes of the graph.
Asymptotic Notation
• O notation: asymptotic “less than”:
32
Asymptotic notations
• O-notation
33
Asymptotic notations (cont.)
• - notation
34
The Master Theorem
• Given: a divide and conquer algorithm
– An algorithm that divides the problem of size n
into a subproblems, each of size n/b
– Let the cost of each stage (i.e., the work to divide
the problem + combine solved subproblems) be
described by the function f(n)
The Master Theorem
• if T(n) = aT(n/b) + f(n) then
n
logb a
f (n) O n logb a
0
T (n) n logb a
log n f (n) n
logb a
c 1
f (n)
f (n) n logb a AND
af (n / b) cf (n) for large n
Using The Master Method
• T(n) = 9T(n/3) + n
– a=9, b=3, f(n) = n
– nlog a = nlog 9 = (n2)
b 3
T ( n) n logb a when f ( n) O n logb a
– Thus the solution is T(n) = (n )2
Thank You