E: \((u,v)\) if there is a doorway between \(u\) and \(v\)
The shape of the rooms is irrelevant.
Each step uses one operation:
list the neighbours of the current room.
Graph Traversal
Objective: visit every vertex and every edge.
Purpose: find interesting structure in the graph.
Compared with a tree traversal:
Tree
Graph
Ordered
Obvious start
Acyclic
Whatever-First Search
WFS(G, s): bag.put(s)while bag is not empty: v = bag.take()if v is UNVISITED: mark v VISITEDfor each w adjacent to v: bag.put(w)
Jeff Erickson, Algorithms
Each type of bag is just an ordering structure.
Bag
Search
Queue
Stack
Priority queue
BFS, by Example
Queue: ________________
Visit order: ____________
d
p
A
C B D
B
A C E
C
B A D E F
D
A C F H
E
B C G
F
C D G
G
E F H
H
D G
WFS(G, s): mark s VISITED bag.put(s)while bag is not empty: v = bag.take()for each w adjacent to v:if w is UNVISITED: mark w VISITED bag.put(w)
BFS
BFS(G):for all u in G.vertices() setLabel(u, UNEXPLORED)for all e in G.edges() setLabel(e, UNEXPLORED)for all v in G.vertices()if getLabel(v)== UNEXPLORED BFS(G, v)
BFS(G, v): queue q setLabel(v, VISITED) q.enqueue(v)while!q.isEmpty() v = q.dequeue()for all w in G.adjacentVertices(v)if getLabel(w)== UNEXPLORED setLabel((v,w), DISCOVERY) setLabel(w, VISITED) q.enqueue(w)elseif getLabel((v,w))== UNEXPLORED setLabel((v,w), CROSS)
Labels every vertex, and labels every edge discovery or cross.
BFS: Observations
The discovery edges form a ________________________.
\(d(v)\) is ______________________________________.
If \((u, w)\) is a cross edge, then \(|d(u) - d(w)| \le\) ________.
To find the path from \(A\) to \(v\): _____________________________.
Number of connected components: __________________________
\(G\) has a cycle exactly when ______________________________
DFS, by Example
Call stack: ________________
Visit order: ____________
p
A
C B D
B
A C E
C
B A D E F
D
A C F H
E
B C G
F
C D G
G
E F H
H
D G
DFS(G, v): mark v VISITEDfor each w adjacent to v:if w is UNVISITED: DFS(G, w)
DFS
DFS(G):for all u in G.vertices() setLabel(u, UNEXPLORED)for all e in G.edges() setLabel(e, UNEXPLORED)for all v in G.vertices()if getLabel(v)== UNEXPLORED DFS(G, v)
DFS(G, v): setLabel(v, VISITED)for all w in G.adjacentVertices(v)if getLabel(w)== UNEXPLORED setLabel((v,w), DISCOVERY) DFS(G, w)elseif getLabel((v,w))== UNEXPLORED setLabel((v,w), BACK)
Where’s the stack?
____________________
Labels every vertex, and labels every edge discovery or back.
DFS: Observations
The discovery edges form a ________________________.
If \((u, w)\) is a back edge, then \(w\) is __________________________ of \(u\).
To find a path from \(A\) to \(v\): _____________________________.
Is it a shortest path? ____________________
Number of connected components: __________________________
\(G\) has a cycle exactly when ______________________________