SlideShare a Scribd company logo
1 of 42
Advanced
DFS
&
BFS
HKOI Training 2004 1
Advanced
Depth-First Search and Breadth-First Search
Advanced
DFS
&
BFS
HKOI Training 2004 2
Overview
• Depth-first search (DFS)
• DFS Forest
• Breadth-first search (BFS)
• Some variants of DFS and BFS
• Graph modeling
Advanced
DFS
&
BFS
HKOI Training 2004 3
Prerequisites
• Elementary graph theory
• Implementations of DFS and BFS
Advanced
DFS
&
BFS
HKOI Training 2004 4
What is a graph?
• A set of vertices and edges
vertex
edge
Advanced
DFS
&
BFS
HKOI Training 2004 5
Trees and related terms
root
siblings
descendents children
ancestors
parent
Advanced
DFS
&
BFS
HKOI Training 2004 6
What is graph traversal?
• Given: a graph
• Goal: visit all (or some) vertices and
edges of the graph using some strategy
• Two simple strategies:
– Depth-first search
– Breadth-first search
Advanced
DFS
&
BFS
HKOI Training 2004 7
Depth-first search (DFS)
• A graph searching method
• Algorithm:
at any time, go further (depth) if you
can; otherwise, retreat
Advanced
DFS
&
BFS
HKOI Training 2004 8
DFS (Pseudo code)
DFS (vertex u) {
mark u as visited
for each vertex v directly reachable from u
if v is unvisited
DFS (v)
}
• Initially all vertices are marked as
unvisited
Advanced
DFS
&
BFS
HKOI Training 2004 9
F
A
B
C
D
E
DFS (Demonstration)
unvisited
visited
Advanced
DFS
&
BFS
HKOI Training 2004 10
“Advanced” DFS
• Apart from just visiting the vertices,
DFS can also provide us with valuable
information
• DFS can be enhanced by introducing:
– birth time and death time of a vertex
• birth time: when the vertex is first visited
• death time: when we retreat from the vertex
– DFS tree
– parent of a vertex (see next slide)
Advanced
DFS
&
BFS
HKOI Training 2004 11
DFS tree / forest
• A rooted tree
• The root is the start vertex
• If v is first visited from u, then u is the
parent of v in the DFS tree
Advanced
DFS
&
BFS
HKOI Training 2004 12
A
F
B
C
D
E
G
H
DFS forest (Demonstration)
unvisited
visited
visited (dead)
A B C D E F G H
birth
death
parent
A
B
C
F
E
D
G
1 2 3 13 10 4 14
12 9 8 16 11 5 15
H
6
7
- A B - A C D C
Advanced
DFS
&
BFS
HKOI Training 2004 13
Classification of edges
• Tree edge
• Forward edge
• Back edge
• Cross edge
• Question: which type of edges is
always absent in an undirected graph?
A
B
C
F
E
D
G
H
Advanced
DFS
&
BFS
HKOI Training 2004 14
Determination of edge types
• How to determine the type of an
arbitrary edge (u, v) after DFS?
• Tree edge
– parent [v] = u
• Forward edge
– not a tree edge; and
– birth [v] > birth [u]; and
– death [v] < death [u]
• How about back edge and cross edge?
Advanced
DFS
&
BFS
HKOI Training 2004 15
Applications of DFS Forests
• Topological sorting (Tsort)
• Strongly-connected components (SCC)
• Some more “advanced” algorithms
Advanced
DFS
&
BFS
HKOI Training 2004 16
Example: SCC
• A graph is strongly-connected if
– for any pair of vertices u and v, one can
go from u to v and from v to u.
• Informally speaking, an SCC of a graph
is a subset of vertices that
– forms a strongly-connected subgraph
– does not form a strongly-connected
subgraph with the addition of any new
vertex
Advanced
DFS
&
BFS
HKOI Training 2004 17
SCC (Illustration)
Advanced
DFS
&
BFS
HKOI Training 2004 18
SCC (Algorithm)
• Compute the DFS forest of the graph G
• Reverse all edges in G to form G’
• Compute a DFS forest of G’, but always
choose the vertex with the latest death
time when choosing the root for a new
tree
• The SCCs of G are the DFS trees in
the DFS forest of G’
Advanced
DFS
&
BFS
HKOI Training 2004 19
A
F
B
C
D
G
H
SCC (Demonstration)
A
F
B
C
D
E
G
H
A B C D E F G H
birth
death
parent
1 2 3 13 10 4 14
12 9 8 16 11 5 15
6
7
- A B - A C D C
D
G
A E B
F
C
H
Advanced
DFS
&
BFS
HKOI Training 2004 20
SCC (Demonstration)
D
G
A E B
F
C
H
A
F
B
C
D
G
H
E
Advanced
DFS
&
BFS
HKOI Training 2004 21
Breadth-first search (BFS)
• A graph searching method
• Instead of searching “deeply” along one
path, BFS tries to search all paths at
the same time
• Makes use of a data structure - queue
Advanced
DFS
&
BFS
HKOI Training 2004 22
BFS (Pseudo code)
while queue not empty
dequeue the first vertex u from queue
for each vertex v directly reachable from u
if v is unvisited
enqueue v to queue
mark v as visited
• Initially all vertices except the start
vertex are marked as unvisited and the
queue contains the start vertex only
Advanced
DFS
&
BFS
HKOI Training 2004 23
A
B
C
D
E
F
G
H
I
J
BFS (Demonstration)
unvisited
visited
visited (dequeued)
Queue: A B C F D E H G J I
Advanced
DFS
&
BFS
HKOI Training 2004 24
Applications of BFS
• Shortest paths finding
• Flood-fill (can also be handled by DFS)
Advanced
DFS
&
BFS
HKOI Training 2004 25
Comparisons of DFS and BFS
DFS BFS
Depth-first Breadth-first
Stack Queue
Does not guarantee
shortest paths
Guarantees shortest
paths
Advanced
DFS
&
BFS
HKOI Training 2004 26
Bidirectional search (BDS)
• Searches simultaneously from both the
start vertex and goal vertex
• Commonly implemented as
bidirectional BFS
start goal
Advanced
DFS
&
BFS
HKOI Training 2004 27
Iterative deepening search (IDS)
• Iteratively performs DFS with
increasing depth bound
• Shortest paths are guaranteed
Advanced
DFS
&
BFS
HKOI Training 2004 28
What is graph modeling?
• Conversion of a problem into a graph
problem
• Sometimes a problem can be easily
solved once its underlying graph model
is recognized
• Graph modeling appears almost every
year in NOI or IOI
Advanced
DFS
&
BFS
HKOI Training 2004 29
Basics of graph modeling
• A few steps:
– identify the vertices and the edges
– identify the objective of the problem
– state the objective in graph terms
– implementation:
• construct the graph from the input instance
• run the suitable graph algorithms on the graph
• convert the output to the required format
Advanced
DFS
&
BFS
HKOI Training 2004 30
Simple examples (1)
• Given a grid maze with obstacles, find
a shortest path between two given
points
start
goal
Advanced
DFS
&
BFS
HKOI Training 2004 31
Simple examples (2)
• A student has the phone numbers of
some other students
• Suppose you know all pairs (A, B) such
that A has B’s number
• Now you want to know Alan’s number,
what is the minimum number of calls
you need to make?
Advanced
DFS
&
BFS
HKOI Training 2004 32
Simple examples (2)
• Vertex: student
• Edge: whether A has B’s number
• Add an edge from A to B if A has B’s
number
• Problem: find a shortest path from your
vertex to Alan’s vertex
Advanced
DFS
&
BFS
HKOI Training 2004 33
Complex examples (1)
• Same settings as simple example 1
• You know a trick – walking through an
obstacle! However, it can be used for
only once
• What should a vertex represent?
– your position only?
– your position + whether you have used the
trick
Advanced
DFS
&
BFS
HKOI Training 2004 34
Complex examples (1)
• A vertex is in the form (position, used)
• The vertices are divided into two
groups
– trick used
– trick not used
Advanced
DFS
&
BFS
HKOI Training 2004 35
Complex examples (1)
start
goal
unused
used
start goal
goal
Advanced
DFS
&
BFS
HKOI Training 2004 36
Complex examples (2)
• The famous 8-puzzle
• Given a state, find the moves that bring
it to the goal state
1 2 3
4 5 6
7 8
Advanced
DFS
&
BFS
HKOI Training 2004 37
Complex examples (2)
• What does a vertex represent?
– the position of the empty square?
– the number of tiles that are in wrong
positions?
– the state (the positions of the eight tiles)
• What are the edges?
• What is the equivalent graph problem?
Advanced
DFS
&
BFS
HKOI Training 2004 38
Complex examples (2)
1 2 3
4 5 6
7 8
1 2 3
4 5 6
7 8
1 2 3
4 5
7 8 6
1 2 3
4 6
7 5 8
1 2 3
4 5 6
7 8
1 2
4 5 3
7 8 6
1 2 3
4 5
7 8 6
Advanced
DFS
&
BFS
HKOI Training 2004 39
Complex examples (3)
• Theseus and Minotaur
– http://www.logicmazes.com/theseus.html
– Extract:
• Theseus must escape from a maze. There is also a
mechanical Minotaur in the maze. For every turn that
Theseus takes, the Minotaur takes two turns. The
Minotaur follows this program for each of his two turns:
• First he tests if he can move horizontally and get closer
to Theseus. If he can, he will move one square
horizontally. If he can’t, he will test if he could move
vertically and get closer to Theseus. If he can, he will
move one square vertically. If he can’t move either
horizontally or vertically, then he just skips that turn.
Advanced
DFS
&
BFS
HKOI Training 2004 40
Complex examples (3)
• What does a vertex represent?
– Theseus’ position
– Minotaur’s position
– Both
• How long do you need to solve the last
maze?
• How long does a well-written program
take to solve it?
Advanced
DFS
&
BFS
HKOI Training 2004 41
Some more examples
• How can the followings be modeled?
– Tilt maze (Single-goal mazes only)
• http://www.clickmazes.com/newtilt/ixtilt2d.htm
– Double title maze
• http://www.clickmazes.com/newtilt/ixtilt.htm
– No-left-turn maze
• http://www.clickmazes.com/noleft/ixnoleft.htm
– Same as complex example 1, but you can
use the trick for k times
Advanced
DFS
&
BFS
HKOI Training 2004 42
Competition problems
• HKOI2000 S – Wormhole Labyrinth
• HKOI2001 S – A Node Too Far
• HKOI2004 S – Teacher’s Problem *
• TFT2001 – OIMan *
• TFT2002 – Bomber Man *
• NOI2001 – cung1 ming4 dik7 daa2 zi6 jyun4
• IOI2000 – Walls *
• IOI2002 – Troublesome Frog
• IOI2003 – Amazing Robots *

More Related Content

Similar to 04a_dfsbfs.ppt

Topological Sort Algorithm.pptx
Topological Sort Algorithm.pptxTopological Sort Algorithm.pptx
Topological Sort Algorithm.pptxMuhammadShafi89
 
The game of cops and robbers
The game of cops and robbersThe game of cops and robbers
The game of cops and robbersSiyoung Oh
 
Unit ii divide and conquer -2
Unit ii divide and conquer -2Unit ii divide and conquer -2
Unit ii divide and conquer -2subhashchandra197
 
bfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxbfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxsaurabhpandey679381
 
uninformed search part 1.pptx
uninformed search part 1.pptxuninformed search part 1.pptx
uninformed search part 1.pptxMUZAMILALI48
 
bag-of-words models
bag-of-words models bag-of-words models
bag-of-words models Xiaotao Zou
 
Search algorithms master
Search algorithms masterSearch algorithms master
Search algorithms masterHossam Hassan
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFSRajandeep Gill
 
DFS & BFS in Computer Algorithm
DFS & BFS in Computer AlgorithmDFS & BFS in Computer Algorithm
DFS & BFS in Computer AlgorithmMeghaj Mallick
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Shuvongkor Barman
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data StructureKeno benti
 
Search tree & graph
Search tree & graphSearch tree & graph
Search tree & graphMichael Jo
 

Similar to 04a_dfsbfs.ppt (20)

130210107039 2130702
130210107039 2130702130210107039 2130702
130210107039 2130702
 
Topological Sort Algorithm.pptx
Topological Sort Algorithm.pptxTopological Sort Algorithm.pptx
Topological Sort Algorithm.pptx
 
The game of cops and robbers
The game of cops and robbersThe game of cops and robbers
The game of cops and robbers
 
Chapter 3.pptx
Chapter 3.pptxChapter 3.pptx
Chapter 3.pptx
 
Unit ii divide and conquer -2
Unit ii divide and conquer -2Unit ii divide and conquer -2
Unit ii divide and conquer -2
 
bfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxbfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptx
 
uninformed search part 1.pptx
uninformed search part 1.pptxuninformed search part 1.pptx
uninformed search part 1.pptx
 
kumattt).pptx
kumattt).pptxkumattt).pptx
kumattt).pptx
 
Graphs
GraphsGraphs
Graphs
 
Graphs
GraphsGraphs
Graphs
 
bag-of-words models
bag-of-words models bag-of-words models
bag-of-words models
 
Search algorithms master
Search algorithms masterSearch algorithms master
Search algorithms master
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
 
U1 L5 DAA.pdf
U1 L5 DAA.pdfU1 L5 DAA.pdf
U1 L5 DAA.pdf
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
DFS & BFS in Computer Algorithm
DFS & BFS in Computer AlgorithmDFS & BFS in Computer Algorithm
DFS & BFS in Computer Algorithm
 
Graphs (1)
Graphs (1)Graphs (1)
Graphs (1)
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
Search tree & graph
Search tree & graphSearch tree & graph
Search tree & graph
 

Recently uploaded

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 

Recently uploaded (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 

04a_dfsbfs.ppt

  • 1. Advanced DFS & BFS HKOI Training 2004 1 Advanced Depth-First Search and Breadth-First Search
  • 2. Advanced DFS & BFS HKOI Training 2004 2 Overview • Depth-first search (DFS) • DFS Forest • Breadth-first search (BFS) • Some variants of DFS and BFS • Graph modeling
  • 3. Advanced DFS & BFS HKOI Training 2004 3 Prerequisites • Elementary graph theory • Implementations of DFS and BFS
  • 4. Advanced DFS & BFS HKOI Training 2004 4 What is a graph? • A set of vertices and edges vertex edge
  • 5. Advanced DFS & BFS HKOI Training 2004 5 Trees and related terms root siblings descendents children ancestors parent
  • 6. Advanced DFS & BFS HKOI Training 2004 6 What is graph traversal? • Given: a graph • Goal: visit all (or some) vertices and edges of the graph using some strategy • Two simple strategies: – Depth-first search – Breadth-first search
  • 7. Advanced DFS & BFS HKOI Training 2004 7 Depth-first search (DFS) • A graph searching method • Algorithm: at any time, go further (depth) if you can; otherwise, retreat
  • 8. Advanced DFS & BFS HKOI Training 2004 8 DFS (Pseudo code) DFS (vertex u) { mark u as visited for each vertex v directly reachable from u if v is unvisited DFS (v) } • Initially all vertices are marked as unvisited
  • 9. Advanced DFS & BFS HKOI Training 2004 9 F A B C D E DFS (Demonstration) unvisited visited
  • 10. Advanced DFS & BFS HKOI Training 2004 10 “Advanced” DFS • Apart from just visiting the vertices, DFS can also provide us with valuable information • DFS can be enhanced by introducing: – birth time and death time of a vertex • birth time: when the vertex is first visited • death time: when we retreat from the vertex – DFS tree – parent of a vertex (see next slide)
  • 11. Advanced DFS & BFS HKOI Training 2004 11 DFS tree / forest • A rooted tree • The root is the start vertex • If v is first visited from u, then u is the parent of v in the DFS tree
  • 12. Advanced DFS & BFS HKOI Training 2004 12 A F B C D E G H DFS forest (Demonstration) unvisited visited visited (dead) A B C D E F G H birth death parent A B C F E D G 1 2 3 13 10 4 14 12 9 8 16 11 5 15 H 6 7 - A B - A C D C
  • 13. Advanced DFS & BFS HKOI Training 2004 13 Classification of edges • Tree edge • Forward edge • Back edge • Cross edge • Question: which type of edges is always absent in an undirected graph? A B C F E D G H
  • 14. Advanced DFS & BFS HKOI Training 2004 14 Determination of edge types • How to determine the type of an arbitrary edge (u, v) after DFS? • Tree edge – parent [v] = u • Forward edge – not a tree edge; and – birth [v] > birth [u]; and – death [v] < death [u] • How about back edge and cross edge?
  • 15. Advanced DFS & BFS HKOI Training 2004 15 Applications of DFS Forests • Topological sorting (Tsort) • Strongly-connected components (SCC) • Some more “advanced” algorithms
  • 16. Advanced DFS & BFS HKOI Training 2004 16 Example: SCC • A graph is strongly-connected if – for any pair of vertices u and v, one can go from u to v and from v to u. • Informally speaking, an SCC of a graph is a subset of vertices that – forms a strongly-connected subgraph – does not form a strongly-connected subgraph with the addition of any new vertex
  • 17. Advanced DFS & BFS HKOI Training 2004 17 SCC (Illustration)
  • 18. Advanced DFS & BFS HKOI Training 2004 18 SCC (Algorithm) • Compute the DFS forest of the graph G • Reverse all edges in G to form G’ • Compute a DFS forest of G’, but always choose the vertex with the latest death time when choosing the root for a new tree • The SCCs of G are the DFS trees in the DFS forest of G’
  • 19. Advanced DFS & BFS HKOI Training 2004 19 A F B C D G H SCC (Demonstration) A F B C D E G H A B C D E F G H birth death parent 1 2 3 13 10 4 14 12 9 8 16 11 5 15 6 7 - A B - A C D C D G A E B F C H
  • 20. Advanced DFS & BFS HKOI Training 2004 20 SCC (Demonstration) D G A E B F C H A F B C D G H E
  • 21. Advanced DFS & BFS HKOI Training 2004 21 Breadth-first search (BFS) • A graph searching method • Instead of searching “deeply” along one path, BFS tries to search all paths at the same time • Makes use of a data structure - queue
  • 22. Advanced DFS & BFS HKOI Training 2004 22 BFS (Pseudo code) while queue not empty dequeue the first vertex u from queue for each vertex v directly reachable from u if v is unvisited enqueue v to queue mark v as visited • Initially all vertices except the start vertex are marked as unvisited and the queue contains the start vertex only
  • 23. Advanced DFS & BFS HKOI Training 2004 23 A B C D E F G H I J BFS (Demonstration) unvisited visited visited (dequeued) Queue: A B C F D E H G J I
  • 24. Advanced DFS & BFS HKOI Training 2004 24 Applications of BFS • Shortest paths finding • Flood-fill (can also be handled by DFS)
  • 25. Advanced DFS & BFS HKOI Training 2004 25 Comparisons of DFS and BFS DFS BFS Depth-first Breadth-first Stack Queue Does not guarantee shortest paths Guarantees shortest paths
  • 26. Advanced DFS & BFS HKOI Training 2004 26 Bidirectional search (BDS) • Searches simultaneously from both the start vertex and goal vertex • Commonly implemented as bidirectional BFS start goal
  • 27. Advanced DFS & BFS HKOI Training 2004 27 Iterative deepening search (IDS) • Iteratively performs DFS with increasing depth bound • Shortest paths are guaranteed
  • 28. Advanced DFS & BFS HKOI Training 2004 28 What is graph modeling? • Conversion of a problem into a graph problem • Sometimes a problem can be easily solved once its underlying graph model is recognized • Graph modeling appears almost every year in NOI or IOI
  • 29. Advanced DFS & BFS HKOI Training 2004 29 Basics of graph modeling • A few steps: – identify the vertices and the edges – identify the objective of the problem – state the objective in graph terms – implementation: • construct the graph from the input instance • run the suitable graph algorithms on the graph • convert the output to the required format
  • 30. Advanced DFS & BFS HKOI Training 2004 30 Simple examples (1) • Given a grid maze with obstacles, find a shortest path between two given points start goal
  • 31. Advanced DFS & BFS HKOI Training 2004 31 Simple examples (2) • A student has the phone numbers of some other students • Suppose you know all pairs (A, B) such that A has B’s number • Now you want to know Alan’s number, what is the minimum number of calls you need to make?
  • 32. Advanced DFS & BFS HKOI Training 2004 32 Simple examples (2) • Vertex: student • Edge: whether A has B’s number • Add an edge from A to B if A has B’s number • Problem: find a shortest path from your vertex to Alan’s vertex
  • 33. Advanced DFS & BFS HKOI Training 2004 33 Complex examples (1) • Same settings as simple example 1 • You know a trick – walking through an obstacle! However, it can be used for only once • What should a vertex represent? – your position only? – your position + whether you have used the trick
  • 34. Advanced DFS & BFS HKOI Training 2004 34 Complex examples (1) • A vertex is in the form (position, used) • The vertices are divided into two groups – trick used – trick not used
  • 35. Advanced DFS & BFS HKOI Training 2004 35 Complex examples (1) start goal unused used start goal goal
  • 36. Advanced DFS & BFS HKOI Training 2004 36 Complex examples (2) • The famous 8-puzzle • Given a state, find the moves that bring it to the goal state 1 2 3 4 5 6 7 8
  • 37. Advanced DFS & BFS HKOI Training 2004 37 Complex examples (2) • What does a vertex represent? – the position of the empty square? – the number of tiles that are in wrong positions? – the state (the positions of the eight tiles) • What are the edges? • What is the equivalent graph problem?
  • 38. Advanced DFS & BFS HKOI Training 2004 38 Complex examples (2) 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 7 8 6 1 2 3 4 6 7 5 8 1 2 3 4 5 6 7 8 1 2 4 5 3 7 8 6 1 2 3 4 5 7 8 6
  • 39. Advanced DFS & BFS HKOI Training 2004 39 Complex examples (3) • Theseus and Minotaur – http://www.logicmazes.com/theseus.html – Extract: • Theseus must escape from a maze. There is also a mechanical Minotaur in the maze. For every turn that Theseus takes, the Minotaur takes two turns. The Minotaur follows this program for each of his two turns: • First he tests if he can move horizontally and get closer to Theseus. If he can, he will move one square horizontally. If he can’t, he will test if he could move vertically and get closer to Theseus. If he can, he will move one square vertically. If he can’t move either horizontally or vertically, then he just skips that turn.
  • 40. Advanced DFS & BFS HKOI Training 2004 40 Complex examples (3) • What does a vertex represent? – Theseus’ position – Minotaur’s position – Both • How long do you need to solve the last maze? • How long does a well-written program take to solve it?
  • 41. Advanced DFS & BFS HKOI Training 2004 41 Some more examples • How can the followings be modeled? – Tilt maze (Single-goal mazes only) • http://www.clickmazes.com/newtilt/ixtilt2d.htm – Double title maze • http://www.clickmazes.com/newtilt/ixtilt.htm – No-left-turn maze • http://www.clickmazes.com/noleft/ixnoleft.htm – Same as complex example 1, but you can use the trick for k times
  • 42. Advanced DFS & BFS HKOI Training 2004 42 Competition problems • HKOI2000 S – Wormhole Labyrinth • HKOI2001 S – A Node Too Far • HKOI2004 S – Teacher’s Problem * • TFT2001 – OIMan * • TFT2002 – Bomber Man * • NOI2001 – cung1 ming4 dik7 daa2 zi6 jyun4 • IOI2000 – Walls * • IOI2002 – Troublesome Frog • IOI2003 – Amazing Robots *