Identity
MD.MAHFUZUL YAMIN
ID:141-15-3429
SEC:F
DEPARTMENT OF CSE
DAFFODIL INTERNATIONAL UNIVERSITY
Topic
Depth-First Search
Think Stack
Breadth-First Search
Think Queue
Depth-First Search
 Search “deeper” in the graph whenever possible
 Edges are explored out of the most recently
discovered vertex v that still has unexplored edges
• After all edges of v have been explored, the search
“backtracks” from the parent of v
• The process continues until all vertices reachable from the
original source have been discovered
• If undiscovered vertices remain, choose one of them as a
new source and repeat the search from that vertex
• DFS creates a “depth-first forest”
1 2
5 4
3
Depth-first search: Directed graphs
 The algorithm is essentially the same as for undirected graphs, the
difference residing in the interpretation of the word "adjacent".
 In a directed graph, node w is adjacent to node v if the directed edge (v,
w) exists.
 If (v, w) exists but (w, v) does not, then w is adjacent to v
but v is not adjacent to w.
 With this change of interpretation the procedures dfs and search apply
equally well in the case of a directed graph.
DFS Example
source
vertex
DFS Example
1 | | |
|||
| |
source
vertex
d f
DFS Example
1 | | |
|||
2 | |
source
vertex
d f
DFS Example
1 | | |
||3 |
2 | |
source
vertex
d f
DFS Example
1 | | |
||3 | 4
2 | |
source
vertex
d f
DFS Example
1 | | |
|5 |3 | 4
2 | |
source
vertex
d f
DFS Example
1 | | |
|5 | 63 | 4
2 | |
source
vertex
d f
DFS Example
1 | | |
|5 | 63 | 4
2 | 7 |
source
vertex
d f
DFS Example
1 | 8 | |
|5 | 63 | 4
2 | 7 |
source
vertex
d f
DFS Example
1 | 8 | |
|5 | 63 | 4
2 | 7 9 |
source
vertex
d f
DFS Example
1 | 8 | |
|5 | 63 | 4
2 | 7 9 |10
source
vertex
d f
DFS Example
1 | 8 |11 |
|5 | 63 | 4
2 | 7 9 |10
source
vertex
d f
DFS Example
1 |12 8 |11 |
|5 | 63 | 4
2 | 7 9 |10
source
vertex
d f
DFS Example
1 |12 8 |11 13|
|5 | 63 | 4
2 | 7 9 |10
source
vertex
d f
DFS Example
1 |12 8 |11 13|
14|5 | 63 | 4
2 | 7 9 |10
source
vertex
d f
DFS Example
1 |12 8 |11 13|
14|155 | 63 | 4
2 | 7 9 |10
source
vertex
d f
DFS Example
1 |12 8 |11 13|16
14|155 | 63 | 4
2 | 7 9 |10
source
vertex
d f
All vertex are visited
Breadth-first search
23
• In graph theory, breadth-first
search (BFS) is a graph search
algorithm that begins at the
root node and explores all the
neighboring nodes.
• Then for each of those
nearest nodes, it explores
their unexplored neighbor
nodes, and so on, until it finds
the goal.
Adjacency Matrix
Adjacency
List
BFS: Start with Node 5
7
1
5
4
3
2
6
5 1 2 0 4 3 7 6
0
That’s all
  

DFS & BFS Graph