SlideShare a Scribd company logo
Reference: Data Structures and Algorithm
Analysis in C++ by Weiss Ch. 9
Prepared by Nisha Soms
Graph Traversals
2
Graphs
2
 graph: A data structure containing:
 a set of vertices V, (sometimes called nodes)
 a set of edges E, where an edge
represents a connection between 2 vertices.
 Graph G = (V, E)
 an edge is a pair (v, w) where v, w are in V
 the graph at right:
 V = {a, b, c, d}
 E = {(a, c), (b, c), (b, d), (c, d)}
 degree: number of edges touching a given vertex.
 at right: a=1, b=2, c=3, d=2
a
c
b
d
3
Graph examples
3
 Web pages with links
 Methods in a program that call each other
 Road maps (e.g., Google maps)
 Airline routes
 Facebook friends
 Course pre-requisites
 Family trees
 Paths through a maze
4
Paths
4
 path: A path from vertex a to b is a sequence of edges that
can be followed starting from a to reach b.
 can be represented as vertices visited, or edges taken
 example, one path from V to Z: {b, h} or {V, X, Z}
 What are two paths from U to Y?
 path length: Number of vertices
or edges contained in the path.
 neighbor or adjacent: Two vertices
connected directly by an edge.
 example: V and X
X
U
V
W
Z
Y
a
c
b
e
d
f
g
h
5
Reachability & Connectedness
5
 reachable: Vertex a is reachable from b
if a path exists from a to b.
 connected: A graph is connected if every
vertex is reachable from any other.
 strongly connected: When every vertex
has an edge to every other vertex.
X
U
V
W
Z
Y
a
c
b
e
d
f
g
h
a
c
b
d
a
c
b
d
e
6
Loops and cycles
6
 cycle: A path that begins and ends at the same node.
 example: {b, g, f, c, a} or {V, X, Y, W, U, V}.
 example: {c, d, a} or {U, W, V, U}.
 acyclic graph: One that does
not contain any cycles.
 loop: An edge directly from
a node to itself.
 Many graphs don't allow loops.
X
U
V
W
Z
Y
a
c
b
e
d
f
g
h
7
Weighted graphs
7
 weight: Cost associated with a given edge.
 Some graphs have weighted edges, and some are
unweighted.
 Edges in an unweighted graph can be thought of as having
equal weight (e.g. all 0, or all 1, etc.)
 Most graphs do not allow negative weights.
 example: graph of airline flights, weighted by miles
between cities:
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
8
Directed graphs
8
 directed graph ("digraph"): One where edges are one-way
connections between vertices.
 If graph is directed, a vertex has a separate in/out degree.
 A digraph can be weighted or unweighted.
 Is the graph below connected? Why or why not?
a
d
b
e
g
f
c
9
Linked Lists, Trees, Graphs
9
 A binary tree is a graph with some restrictions:
 The tree is an unweighted, directed, acyclic graph (DAG).
 Each node's in-degree is at most 1, and out-degree is at most
2.
 There is exactly one path from the root to every node.
 A linked list is also a graph:
 Unweighted DAG.
 In/out degree of at most 1 for all nodes.
F
B
A E
K
H
J
G
A B D
C
10
Searching for paths
10
 Searching for a path from one vertex to another:
 Sometimes, we just want any path (or want to know there is a
path).
 Sometimes, we want to minimize path length (# of edges).
 Sometimes, we want to minimize path cost (sum of edge
weights).
 What is the shortest path from MIA to SFO?
Which path has the minimum cost?
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
$500
11
Depth-first search
11
 Depth-first search (DFS): Finds a path between two
vertices by exploring each possible path as far as possible
before backtracking.
 Often implemented recursively.
 Many graph algorithms involve visiting or marking vertices.
 Depth-first paths from a to all vertices (assuming ABC edge
order):
 to b: {a, b}
 to c: {a, b, e, f, c}
 to d: {a, d}
 to e: {a, b, e}
 to f: {a, b, e, f}
a
e
b c
h
g
d f
12
DFS pseudocode
12
function dfs(v1, v2):
dfs(v1, v2, { }).
function dfs(v1, v2, path):
path += v1.
mark v1 as visited.
if v1 is v2:
a path is found!
for each unvisited neighbor n of v1:
if dfs(n, v2, path) finds a path: a path is found!
path -= v1. // path is not found.
a
e
b c
h
g
d f
13
DFS observations
13
 discovery: DFS is guaranteed to
find a path if one exists.
 retrieval: It is easy to retrieve exactly
what the path is (the sequence of
edges taken) if we find it
 optimality: not optimal. DFS is guaranteed to find a path,
not necessarily the best/shortest path
 Example: dfs(a, f) returns {a, d, c, f} rather than {a, d, f}.
a
e
b c
h
g
d f
14
Breadth-first search
14
 Breadth-first search (BFS): Finds a path between two
nodes by taking one step down all paths and then
immediately backtracking.
 Often implemented by maintaining a queue of vertices to visit.
 BFS always returns the shortest path (the one with the
fewest edges) between the start and the end vertices.
 to b: {a, b}
 to c: {a, e, f, c}
 to d: {a, d}
 to e: {a, e}
 to f: {a, e, f}
 to g: {a, d, g}
 to h: {a, d, h}
a
e
b c
h
g
d f
15
BFS pseudocode
15
function bfs(v1, v2):
queue := {v1}.
mark v1 as visited.
while queue is not empty:
v := queue.removeFirst().
if v is v2:
a path is found!
for each unvisited neighbor n of v:
mark n as visited.
queue.addLast(n).
// path is not found.
a
e
b c
h
g
d f
16
BFS observations
16
 Optimality:
 always finds the shortest path (fewest edges).
 In unweighted graphs, finds optimal cost path.
 In weighted graphs, not always optimal cost.
 Retrieval: harder to reconstruct the actual sequence of
vertices or edges in the path once you find it
 conceptually, BFS is exploring many possible paths in parallel,
so it's not easy to store a path array/list in progress
 solution: We can keep track of the path by storing
predecessors for each vertex (each vertex can store a
reference to a previous vertex).
 DFS uses less memory than BFS, easier to reconstruct the
a
e
b c
h
g
d f
17
DFS, BFS runtime
17
 What is the expected runtime of DFS and BFS, in terms of
the number of vertices V and the number of edges E ?
 Answer: O(|V| + |E|)
 where |V| = number of vertices, |E| = number of edges
 Must potentially visit every node and/or examine every edge
once.
18
BFS that finds path
18
function bfs(v1, v2):
queue := {v1}.
mark v1 as visited.
while queue is not empty:
v := queue.removeFirst().
if v is v2:
a path is found! (reconstruct it by following .prev back
to v1.)
for each unvisited neighbor n of v:
mark n as visited. (set n.prev = v.)
queue.addLast(n).
// path is not found.
a
e
b c
h
g
d f
prev
Thank you

More Related Content

What's hot

Hash table
Hash tableHash table
Hash table
Rajendran
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
Rajandeep Gill
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
Amrinder Arora
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
shameen khan
 
Singly link list
Singly link listSingly link list
Singly link list
Rojin Khadka
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
Kevin Jadiya
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queues
Ramzi Alqrainy
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
Abrish06
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
Shareb Ismaeel
 
Breadth first search signed
Breadth first search signedBreadth first search signed
Breadth first search signed
AfshanKhan51
 
Graph representation
Graph representationGraph representation
Graph representationTech_MX
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
Rabin BK
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
Dr Shashikant Athawale
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
ManishPrajapati78
 
stack & queue
stack & queuestack & queue
stack & queue
manju rani
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
Protap Mondal
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithm
Gaurav Kolekar
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
Hinal Lunagariya
 
Hash tables
Hash tablesHash tables
Hash tables
Rajendran
 

What's hot (20)

Hash table
Hash tableHash table
Hash table
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Singly link list
Singly link listSingly link list
Singly link list
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queues
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 
Breadth first search signed
Breadth first search signedBreadth first search signed
Breadth first search signed
 
Graph representation
Graph representationGraph representation
Graph representation
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
stack & queue
stack & queuestack & queue
stack & queue
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithm
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
 
Hash tables
Hash tablesHash tables
Hash tables
 
B trees dbms
B trees dbmsB trees dbms
B trees dbms
 

Similar to Depth First Search and Breadth First Search

Talk on Graph Theory - I
Talk on Graph Theory - ITalk on Graph Theory - I
Talk on Graph Theory - I
Anirudh Raja
 
22-graphs1-dfs-bfs.ppt
22-graphs1-dfs-bfs.ppt22-graphs1-dfs-bfs.ppt
22-graphs1-dfs-bfs.ppt
KarunaBiswas3
 
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
chandrashekarr799
 
09-graphs.ppt
09-graphs.ppt09-graphs.ppt
09-graphs.ppt
Dr. Ajay Kumar Singh
 
Graph therory
Graph theroryGraph therory
Graph therory
mohanrathod18
 
Tn 110 lecture 8
Tn 110 lecture 8Tn 110 lecture 8
Tn 110 lecture 8
ITNet
 
Breadth first search
Breadth first searchBreadth first search
Breadth first search
Sazzad Hossain
 
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
ARVIND SARDAR
 
Graphs
GraphsGraphs
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
Edhole.com
 
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
abdulrafaychaudhry
 
19-graph1 (1).ppt
19-graph1 (1).ppt19-graph1 (1).ppt
19-graph1 (1).ppt
Himajanaidu2
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
ARVIND SARDAR
 
Graphs in data structures
Graphs in data structuresGraphs in data structures
Graphs in data structures
Savit Chandra
 
Graphs
GraphsGraphs
graph.pptx
graph.pptxgraph.pptx
graph.pptx
hijigaf
 
Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashingVictor Palmar
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
TalhaFarooqui12
 

Similar to Depth First Search and Breadth First Search (20)

Talk on Graph Theory - I
Talk on Graph Theory - ITalk on Graph Theory - I
Talk on Graph Theory - I
 
22-graphs1-dfs-bfs.ppt
22-graphs1-dfs-bfs.ppt22-graphs1-dfs-bfs.ppt
22-graphs1-dfs-bfs.ppt
 
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
22-graphs1-dfs-bfs.ppt odiehehei7hoh97ho7bi6vi6go7gp
 
09-graphs.ppt
09-graphs.ppt09-graphs.ppt
09-graphs.ppt
 
Graph therory
Graph theroryGraph therory
Graph therory
 
Tn 110 lecture 8
Tn 110 lecture 8Tn 110 lecture 8
Tn 110 lecture 8
 
Breadth first search
Breadth first searchBreadth first search
Breadth first search
 
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
 
Graphs
GraphsGraphs
Graphs
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
 
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
Graphical reprsentation dsa (DATA STRUCTURE ALGORITHM)
 
19-graph1 (1).ppt
19-graph1 (1).ppt19-graph1 (1).ppt
19-graph1 (1).ppt
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
 
Graphs in data structures
Graphs in data structuresGraphs in data structures
Graphs in data structures
 
Graphs
GraphsGraphs
Graphs
 
graph.pptx
graph.pptxgraph.pptx
graph.pptx
 
Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashing
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
 
Magtibay buk bind#2
Magtibay buk bind#2Magtibay buk bind#2
Magtibay buk bind#2
 
Graps 2
Graps 2Graps 2
Graps 2
 

More from Nisha Soms

Asymptotic analysis
Asymptotic analysisAsymptotic analysis
Asymptotic analysis
Nisha Soms
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
Nisha Soms
 
Notion of an algorithm
Notion of an algorithmNotion of an algorithm
Notion of an algorithm
Nisha Soms
 
Divide and conquer strategy
Divide and conquer strategyDivide and conquer strategy
Divide and conquer strategy
Nisha Soms
 
Merge sort
Merge sortMerge sort
Merge sort
Nisha Soms
 
Linear and Binary search
Linear and Binary searchLinear and Binary search
Linear and Binary search
Nisha Soms
 

More from Nisha Soms (6)

Asymptotic analysis
Asymptotic analysisAsymptotic analysis
Asymptotic analysis
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
Notion of an algorithm
Notion of an algorithmNotion of an algorithm
Notion of an algorithm
 
Divide and conquer strategy
Divide and conquer strategyDivide and conquer strategy
Divide and conquer strategy
 
Merge sort
Merge sortMerge sort
Merge sort
 
Linear and Binary search
Linear and Binary searchLinear and Binary search
Linear and Binary search
 

Recently uploaded

Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
gb193092
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 

Recently uploaded (20)

Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 

Depth First Search and Breadth First Search

  • 1. Reference: Data Structures and Algorithm Analysis in C++ by Weiss Ch. 9 Prepared by Nisha Soms Graph Traversals
  • 2. 2 Graphs 2  graph: A data structure containing:  a set of vertices V, (sometimes called nodes)  a set of edges E, where an edge represents a connection between 2 vertices.  Graph G = (V, E)  an edge is a pair (v, w) where v, w are in V  the graph at right:  V = {a, b, c, d}  E = {(a, c), (b, c), (b, d), (c, d)}  degree: number of edges touching a given vertex.  at right: a=1, b=2, c=3, d=2 a c b d
  • 3. 3 Graph examples 3  Web pages with links  Methods in a program that call each other  Road maps (e.g., Google maps)  Airline routes  Facebook friends  Course pre-requisites  Family trees  Paths through a maze
  • 4. 4 Paths 4  path: A path from vertex a to b is a sequence of edges that can be followed starting from a to reach b.  can be represented as vertices visited, or edges taken  example, one path from V to Z: {b, h} or {V, X, Z}  What are two paths from U to Y?  path length: Number of vertices or edges contained in the path.  neighbor or adjacent: Two vertices connected directly by an edge.  example: V and X X U V W Z Y a c b e d f g h
  • 5. 5 Reachability & Connectedness 5  reachable: Vertex a is reachable from b if a path exists from a to b.  connected: A graph is connected if every vertex is reachable from any other.  strongly connected: When every vertex has an edge to every other vertex. X U V W Z Y a c b e d f g h a c b d a c b d e
  • 6. 6 Loops and cycles 6  cycle: A path that begins and ends at the same node.  example: {b, g, f, c, a} or {V, X, Y, W, U, V}.  example: {c, d, a} or {U, W, V, U}.  acyclic graph: One that does not contain any cycles.  loop: An edge directly from a node to itself.  Many graphs don't allow loops. X U V W Z Y a c b e d f g h
  • 7. 7 Weighted graphs 7  weight: Cost associated with a given edge.  Some graphs have weighted edges, and some are unweighted.  Edges in an unweighted graph can be thought of as having equal weight (e.g. all 0, or all 1, etc.)  Most graphs do not allow negative weights.  example: graph of airline flights, weighted by miles between cities: ORD PVD MIA DFW SFO LAX LGA HNL
  • 8. 8 Directed graphs 8  directed graph ("digraph"): One where edges are one-way connections between vertices.  If graph is directed, a vertex has a separate in/out degree.  A digraph can be weighted or unweighted.  Is the graph below connected? Why or why not? a d b e g f c
  • 9. 9 Linked Lists, Trees, Graphs 9  A binary tree is a graph with some restrictions:  The tree is an unweighted, directed, acyclic graph (DAG).  Each node's in-degree is at most 1, and out-degree is at most 2.  There is exactly one path from the root to every node.  A linked list is also a graph:  Unweighted DAG.  In/out degree of at most 1 for all nodes. F B A E K H J G A B D C
  • 10. 10 Searching for paths 10  Searching for a path from one vertex to another:  Sometimes, we just want any path (or want to know there is a path).  Sometimes, we want to minimize path length (# of edges).  Sometimes, we want to minimize path cost (sum of edge weights).  What is the shortest path from MIA to SFO? Which path has the minimum cost? ORD PVD MIA DFW SFO LAX LGA HNL $500
  • 11. 11 Depth-first search 11  Depth-first search (DFS): Finds a path between two vertices by exploring each possible path as far as possible before backtracking.  Often implemented recursively.  Many graph algorithms involve visiting or marking vertices.  Depth-first paths from a to all vertices (assuming ABC edge order):  to b: {a, b}  to c: {a, b, e, f, c}  to d: {a, d}  to e: {a, b, e}  to f: {a, b, e, f} a e b c h g d f
  • 12. 12 DFS pseudocode 12 function dfs(v1, v2): dfs(v1, v2, { }). function dfs(v1, v2, path): path += v1. mark v1 as visited. if v1 is v2: a path is found! for each unvisited neighbor n of v1: if dfs(n, v2, path) finds a path: a path is found! path -= v1. // path is not found. a e b c h g d f
  • 13. 13 DFS observations 13  discovery: DFS is guaranteed to find a path if one exists.  retrieval: It is easy to retrieve exactly what the path is (the sequence of edges taken) if we find it  optimality: not optimal. DFS is guaranteed to find a path, not necessarily the best/shortest path  Example: dfs(a, f) returns {a, d, c, f} rather than {a, d, f}. a e b c h g d f
  • 14. 14 Breadth-first search 14  Breadth-first search (BFS): Finds a path between two nodes by taking one step down all paths and then immediately backtracking.  Often implemented by maintaining a queue of vertices to visit.  BFS always returns the shortest path (the one with the fewest edges) between the start and the end vertices.  to b: {a, b}  to c: {a, e, f, c}  to d: {a, d}  to e: {a, e}  to f: {a, e, f}  to g: {a, d, g}  to h: {a, d, h} a e b c h g d f
  • 15. 15 BFS pseudocode 15 function bfs(v1, v2): queue := {v1}. mark v1 as visited. while queue is not empty: v := queue.removeFirst(). if v is v2: a path is found! for each unvisited neighbor n of v: mark n as visited. queue.addLast(n). // path is not found. a e b c h g d f
  • 16. 16 BFS observations 16  Optimality:  always finds the shortest path (fewest edges).  In unweighted graphs, finds optimal cost path.  In weighted graphs, not always optimal cost.  Retrieval: harder to reconstruct the actual sequence of vertices or edges in the path once you find it  conceptually, BFS is exploring many possible paths in parallel, so it's not easy to store a path array/list in progress  solution: We can keep track of the path by storing predecessors for each vertex (each vertex can store a reference to a previous vertex).  DFS uses less memory than BFS, easier to reconstruct the a e b c h g d f
  • 17. 17 DFS, BFS runtime 17  What is the expected runtime of DFS and BFS, in terms of the number of vertices V and the number of edges E ?  Answer: O(|V| + |E|)  where |V| = number of vertices, |E| = number of edges  Must potentially visit every node and/or examine every edge once.
  • 18. 18 BFS that finds path 18 function bfs(v1, v2): queue := {v1}. mark v1 as visited. while queue is not empty: v := queue.removeFirst(). if v is v2: a path is found! (reconstruct it by following .prev back to v1.) for each unvisited neighbor n of v: mark n as visited. (set n.prev = v.) queue.addLast(n). // path is not found. a e b c h g d f prev