0% found this document useful (0 votes)
0 views29 pages

09 GTraverse

The document discusses graph traversal algorithms, specifically Depth-First Search (DFS) and Breadth-First Search (BFS), including their outlines, applications, and analysis of connected components. It covers the classification of edges, properties of active intervals, and the differences between DFS and BFS in terms of processing opportunities. Additionally, it provides pseudocode for implementing these algorithms and their respective complexities.

Uploaded by

wabgdinghan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views29 pages

09 GTraverse

The document discusses graph traversal algorithms, specifically Depth-First Search (DFS) and Breadth-First Search (BFS), including their outlines, applications, and analysis of connected components. It covers the classification of edges, properties of active intervals, and the differences between DFS and BFS in terms of processing opportunities. Additionally, it provides pseudocode for implementing these algorithms and their respective complexities.

Uploaded by

wabgdinghan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

Graph Traversals

Algorithm : Design & Analysis


[11]
In the last class…
 Dynamic Equivalence Relation
 Implementing Dynamic Set by Union-Find
 Straight Union-Find
 Making Shorter Tree by Weighted Union
 Compressing Path by Compressing-Find
 Amortized Analysis of wUnion-cFind
Graph Traversals
 Depth-First and Breadth-First Search
 Finding Connected Components
 General Depth-First Search Skeleton
 Depth-First Search Trace
Graph Traversal: an Example
Starting node
A D
Not reachable

B G Breadth-FirstSearch
Search
Breadth-First
Starting node
F C E A D
Depth-FirstSearch
Depth-First Search
B G

Edges only “checked” F C E


Not reachable
Outline of Depth-First Search
AAvertex
vertexmust
mustbe
beexact
exactone
oneofofthree
three
differentstatus:
different status:
undiscovered
undiscovered
 dfs(G,v) discoveredbut
discovered butnot
notfinished
finished
finished
finished
 Mark v as “discovered”.
 For each vertex w that edge vw is in G:
 If w is undiscovered: That is: exploring vw, visiting w,
 dfs(G,w) exploring from there as much as
possible, and backtrack from w to v.
 Otherwise:
 “Check” vw without visiting w.
 Mark v as “finished”.
Outline of Breadth First Search
 Bfs(G,s)
 Mark s as “discovered”;
 enqueue(pending,s);
 while (pending is nonempty)
 v=front(pending);
 dequeue(pending, v);
 For each vertex w that edge vw is in G:
 If w is “undiscovered”
 Mark w as “discovered” and enqueue(pending, w)
 Mark v as “finished”;
Graph as Group of Linked-List
2 4 5
6
adjVertices
1 3 7
1 2 3 Undirected graph as a
symmetric directed graph
2 1 Note:3 4
Note:ififthe
thegraph
graphisis
dense,
dense,that
that2 is,
is,|E|
|E|isis
3 1 close2 to
close to|V|V|,2|,matrix
matrix 4 6
may
maybe bepreferred.
Another
preferred.
Another
4 2 3 disadvantage:6
disadvantage:
try
trytotodetermine
determine
5 6 whether
whether(u,v)(u,v)E
E

6 3 4 5 7

7 6
Finding Connected Components
 Input: a symmetric digraph G, with n nodes and 2m edges(interpreted
as an undirected graph), implemented as a array adjVertices[1,…n] of
adjacency lists.
 Output: an array cc[1..n] of component number for each node vi
 void connectedComponents(Intlist[ ] adjVertices, int n,
int[ ] cc) // This is a wrapper procedure
 int[ ] color=new int[n+1];
Depth-first search
 int v;
 <Initialize color array to white for all vertices>
 for (v=1; vn; v++)
 if (color[v]==white)
 ccDFS(adjVertices, color, v, v, cc);
 return
ccDFS: the procedure
 void ccDFS(IntList[ ] adjVertices, int[ ] color, int v, int ccNum, int [ ] cc)//v as
the code of current connected component
 int w;
 IntList remAdj; The elements of
The elements of
remAdjare
remAdj are
 color[v]=gray; neighborsof
ofvv
 cc[v]=ccNum; neighbors
 remAdj=adjVertices[v];
Processingthe
Processing thenext
nextneighbor,
neighbor,
 while (remAdjnil)
 w=first(remAdj); ififexisting,
existing,another
anotherdepth-first
depth-first
 if (color[w]==white) searchtotobe
search beincurred
incurred
 ccDFS(adjVertices, color, w, ccNum, cc);
 remAdj=rest(remAdj);
 color[v]=black;
 return
v finished
Analysis of CC Algorithm
 connectedComponents, the wrapper
 Linear in n (color array initialization+for loop on adjVertices )
 ccDFS, the depth-first searcher
 In one execution of ccDFS on v, the number of instructions(rest(remAdj))
executed is proportional to the size of adjVertices[v].
 Note: (size of adjVertices[v]) is 2m, and the adjacency lists are traveresed
only once.
 So, the complexity is in (m+n)
 Extra space requirements:
 color array
 activation frame stack for recursion
Depth-First Search Trees
DFSforest={(DFS
DFS forest={(DFStree1),
tree1),(DFS
(DFStree2)}
tree2)}

Root of tree 1
B.E
A D
T.E

C.
T. E

E
B. E

B G
D.

E
E

C.

E
T. E

T.E

B.
T.E:tree
T.E: treeedge
edge

T. E
B.E:back
B.E: backedge
edge F C E
C.E C.E
D.E:descendant
D.E: descendant Root of tree 2
edge
edge
C.E:cross
crossedge
edge AAfinished
finishedvertex
vertexisisnever
never
C.E:
revisited,
revisited,such
suchas
asCC
Visits On a Vertex
 Classification for the visits on a vertex
 First visit(exploring): status: whitegray
 (Possibly) multi-visits by backtracking to: status keeps
gray
 Last visit(no more branch-finished): status: grayblack
 Different operations can be done on the vertex or
(selected) incident edges during the different visits on
a specific vertex
Depth-First Search: Generalized
 Input: Array adjVertices for graph G
 Output: Return value depends on application.
 int dfsSweep(IntList[] adjVertices,int n, …)
 int ans;
 <Allocate color array and initialize to white>
 For each vertex v of G, in some order
 if (color[v]==white)
 int vAns=dfs(adjVertices, color, v, …);
 <Process vAns>
 // Continue loop
 return ans;
Depth-First Search: Generalized
 int dfs(IntList[] adjVertices, int[] color, int v, …)
 int w;
 IntList remAdj; IfIfpartial
partialsearch
searchisisused
usedfor
foraa
 int ans; application,tests
application, testsfor
fortermination
termination
 color[v]=gray; maybe
may beinserted
insertedhere.
here.
 <Preorder processing of vertex v>
 remAdj=adjVertices[v]; Specialized for
 while (remAdjnil) connected
 w=first(remAdj); components:
 if (color[w]==white) •parameter added
 <Exploratory processing for tree edge vw> •preorder processing
 int wAns=dfs(adjVertices, color, w, …); inserted – cc[v]=ccNum
 < Backtrack processing for tree edge vw , using wAns>
 else
 <Checking for nontree edge vw>
 remAdj=rest(remAdj);
 <Postorder processing of vertex v, including final computation of ans>
 color[v]=black;
 return ans;
Breadth-First Search: the Skeleton
 Input: Array adjVertices for graph G
 Output: Return value depends on application.
 void bfsSweep(IntList[] adjVertices,int n, …)
 int ans;
 <Allocate color array and initialize to white>
 For each vertex v of G, in some order
 if (color[v]==white)
 void bfs(adjVertices, color, v, …);
 // Continue loop
 return;
Breadth-First Search: the Skeleton

 void bfs(IntList[] adjVertices, int[] color, int v, …)


 int w; IntList remAdj; Queue pending;
 color[v]=gray; enqueue(pending, v);
 while (pending is nonempty)
 w=dequeue(pending); remAdj=adjVertices[w];
 while (remAdjnil)
 x=first(remAdj);
 if (color[x]==white)
 color[x]=gray; enqueue(pending, x);
 remAdj=rest(remAdj);
 <processing of vertex w>
 color[w]=black;
 return ;
DFS vs. BFS Search
 Processing Opportunities for a node
 Depth-first: 2
 At discovering
 At finishing

 Breadth-first: only 1, when de-queued


 At the second processing opportunity for the DFS,
the algorithm can make use of information about
the descendants of the current node.
Time Relation on Changing Color
 Keeping the order in which vertices are encountered for the
first or last time
 A global interger time: 0 as the initial value, incremented
with each color changing for any vertex, and the final
value is 2n
 Array discoverTime: the i th element records the time

vertex vi turns into gray


 Array finishTime: the i th element records the time vertex vi
turns into black
 The active interval for vertex v, denoted as active(v), is the
duration while v is gray, that is:
discoverTime[v], …, finishTime[v]
Depth-First Search Trace
 General DFS skeleton modified to compute discovery and finishing times
and “construct” the depth-first search forest.
 int dfsTraceSweep(IntList[ ] adjVertices,int n, int[ ] discoverTime, int[ ]
finishTime, int[ ] parent)
 int ans; int time=0
 <Allocate color array and initialize to white>
 For each vertex v of G, in some order
 if (color[v]==white)
 parent[v]=-1
 int vAns=dfsTrace(adjVertices, color, v, discoverTime, finishTime,
parent, time );
 // Continue loop
 return ans;
Depth-First Search Trace
 int dfsTrace(intList[ ] adjVertices, int[ ] color, int v, int[ ] discoverTime,
 int[ ] finishTime, int[ ] parent int time)
 int w; IntList remAdj; int ans;
 color[v]=gray; time++; discoverTime[v]=time;
 remAdj=adjVertices[v];
 while (remAdjnil)
 w=first(remAdj);
 if (color[w]==white)
 parent[w]=v;
 int wAns=dfsTrace(adjVertices, color, w, discoverTime, finishTime,
parent, time);
 else <Checking for nontree edge vw>
 remAdj=rest(remAdj);
 time++; finishTime[v]=time; color[v]=black;
 return ans;
Edge Classification
and the Active Intervals
1/10 5/6
B.E
A D
T.E

C.
2/7 T. E

E
B. E

12/13
B G
D.

E The relations are


E

C.

E
T. E

T.E

C.
summarized in the

T. E
F C E next frame
8/9 C.E C.E
3/4 11/14

Time
1 2 3 4 5 6 7 8 9 10 11 12 13
14 A E
B F G
C D
Properties about Active Intervals(1)
 If w is a descendant of v in the DFS forest, then
active(w)active(v), and the inclusion is proper if wv.
 Proof:
 Define a partial order <: w<v iff. w is a proper descendants of v

in its DFS tree. The proof is by induction on <)


 If v is minimal. The only descendant of v is itself. Trivial.

 Assume that for all x<v, if w is a descendant of x, then

active(w)active(x).
 Let w be any proper descendant of v in the DFS tree, there

must be some x such that vx is a tree edge on the tree path to w,


so w is a descendant of x. According to dfsTrace, we have
active(x)active(v), by inductive hypothesis,
active(w)active(v),
Properties about Active Intervals(2)
 If v and w have no ancestor/descendant relationship in the DFS
forest, then their active intervals are disjoint.
 Proof:
 If v and w are in different DFS tree, it is trivially true, since the

trees are processed one by one.


 Otherwise, there must be a vertex c, satisfying that there are

tree paths c to v, and c to w, without edges in common. Let the


leading edges of the two tree path are cy, cz, respectively.
According to dfsTrace, active(y) and active(z) are disjoint.
 We have active(v)active(y), active(w)active(z). So,

active(v) and active(w) are disjoint.


Properties about Active Intervals(3)
 If active(w)active(v), then w is a descendant of v. And if
active(w)active(v), then w is a proper descendant of v.
That is: w is discovered while v is active.
 Proof:
 If w is not a descendant of v, there are two cases:

 v is a proper descendant of w, then active(v)active(w),

so, it is impossible that active(w)active(v), contradiction.


 There is no ancestor/descendant relationship between v

and w, then active(w) and active(v) are disjoint,


contradiction.
Properties about Active Intervals(4)
 If edge vwEG, then
 vw is a cross edge iff. active(w) entirely precedes
active(v).
 vw is a descendant edge iff. there is some third vertex x,
such that active(w)active(x)active(v),
 vw is a tree edge iff. active(w)active(v), and there is no
third vertex x, such that active(w)active(x) active(v),
 vw is a back edge iff. active(v)active(w),
Ancestor/Descendant Relationship
and Directed Path
 That w is a descendant of v
in the DFS forest means
that there is a direct path vk
from v to w in some DFS
undiscovered
tree.
checked
 The path is also a path in G.
vk+2
 However, if there is a direct vk+1
path from v to w in G, is w At the moment
necessarily a descendant of before
v in the DFS forest? vk+3 backtracking
DFS Tree Path
 [White Path Theorem] w is a descendant of v in a DFS
tree iff. at the time v is discovered(just to be changing
color into gray), there is a path in G from v to w
consisting entirely of white vertices.
v

x1 P A white path from v to w


1

xi P2
w
Proof of White Path Theorem
 Proof
  All the vertices in the path are descendants of v.

  by induction on the length k of a white path from v to w.

 When k=0, v=w.

 For k>0, let P=(v, x ,x ,…x =w). There must be some


1 2 k
vertex on P which is discovered during the active interval of
v, e.g. x1, Let xi is earliest discovered among them. Divide P
into P1 from v to xi, and P2 from xi to w. P2 is a white path
with length less than k, so, by inductive hypothesis, w is a
descendant of xi. Note: active(xi)active(v), so xi is a
descendant of v. By transitivity, w is a descendant of v.
Home Assignments
 7.12
 7.14
 7.15
 7.16

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy