L7_Graph Traversal.pptx
L7_Graph Traversal.pptx
Graph Traversal
Dipannita Biswas
Md Mehrab Hossain Opi
Introduction 2
• Let’s consider a different graph today.
• Again each node represents a person today.
• And the edges represent if they came in contact in recent times.
• Let’s say edges represent if two people met each other in the last 7 days.
8 9
0 • So,
1 initially
2 3 ‘cur’4 5= 1.6
8 9
7 8 9
0 1 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
8 9
0 1 1 1 1 0 0 0 0 0
2 3 4
• We will take the first element from the data structure
• Remove it
• Visit all of its adjacent
• Insert them at the end of our data structure.
• So we need a data structure that can remove an element from the
beginning and insert an element at the end with good time complexity.
• Which data structure should we use then?
• The answer is queue.
2 3 4
Queue
1
2 3 4 5 6
5 6 7
Visited Array
0 1 2 3 4 5 6 7 8 9
8 9
0 0
1 1
0 1
0 0
1 0
1 1
0 0 0 0
2 3 4
Queue
3 4 5 6 9 7
5 6 7
Visited Array
0 1 2 3 4 5 6 7 8 9
8 9
0 1 1 1 1 1 1 1
0 0 1
0
2 3 4
Queue
5 6 9 7 8
5 6 7
Visited Array
0 1 2 3 4 5 6 7 8 9
8 9
0 1 1 1 1 1 1 1 1
0 1
2 3 4
5 6 7
8 9
2 3 4
5 6 7
8 9
5 6 7
8 9
1
2 3 4 5 6
5 6 7
0 1 2 3 4 5 6 7 8 9
Visited 0 0
1 1
0 1
0 0
1 0
1 1
0 0 0 0 8 9
Distance - -0 1- 1- 1- 2- 2- - - -
distances[neighbor] = distances[current_vertex] + 1
5 6 7
8 9
4
9
1
7 3
6 2
5 6 7
Visited Array
0 1 2 3 4 5 6 7 8 9
8 9
0 0
1 1
0 1
0 0
1 0 0
1 0
1 0 1
0
9 56
8 2
5 6 7
Visited Array
0 1 2 3 4 5 6 7 8 9
8 9
0 1 1 1 1 0
1 1 1 0
1 1
12
1 14 9
10
13
5
2 8
15
3
7
11
4
6
Thank You.