CS 332: Algorithms
CS 332: Algorithms
Graph Algorithms
Depth-First Search
● Depth-first search is another strategy for
exploring a graph
■ Explore “deeper” in the graph whenever possible
■ Edges are explored out of the most recently
discovered vertex v that still has unexplored edges
■ When all of v’s edges have been explored,
backtrack to the vertex from which v was
discovered
Depth-First Search
● Vertices initially colored white
● Then colored gray when discovered
● Then black when finished
Depth-First Search: The Code
DFS(G) DFS_Visit(u)
{ {
u->color = GREY;
for each vertex u G->V
time = time+1;
{
u->d = time;
u->color = WHITE;
for each v u->Adj[]
}
{
time = 0;
if (v->color == WHITE)
for each vertex u G->V
DFS_Visit(v);
{
}
if (u->color == WHITE)
u->color = BLACK;
DFS_Visit(u);
time = time+1;
}
u->f = time;
}
}
Depth-First Search: The Code
DFS(G) DFS_Visit(u)
{ {
u->color = GREY;
for each vertex u G->V
time = time+1;
{
u->d = time;
u->color = WHITE;
for each v u->Adj[]
}
{
time = 0;
if (v->color == WHITE)
for each vertex u G->V
DFS_Visit(v);
{
}
if (u->color == WHITE)
u->color = BLACK;
DFS_Visit(u);
time = time+1;
}
u->f = time;
}
}
| |
| | |
DFS Example
source
vertex
d f
1 | | |
2 | |
| | |
DFS Example
source
vertex
d f
1 | | |
2 | |
3 | | |
DFS Example
source
vertex
d f
1 | | |
2 | |
3 | 4 | |
DFS Example
source
vertex
d f
1 | | |
2 | |
3 | 4 5 | |
DFS Example
source
vertex
d f
1 | | |
2 | |
3 | 4 5 | 6 |
DFS Example
source
vertex
d f
1 | 8 | |
2 | 7 |
3 | 4 5 | 6 |
DFS Example
source
vertex
d f
1 | 8 | |
2 | 7 |
3 | 4 5 | 6 |
DFS Example
source
vertex
d f
1 | 8 | |
2 | 7 9 |
3 | 4 5 | 6 |
2 | 7 9 |10
3 | 4 5 | 6 |
DFS Example
source
vertex
d f
1 | 8 |11 |
2 | 7 9 |10
3 | 4 5 | 6 |
DFS Example
source
vertex
d f
1 |12 8 |11 |
2 | 7 9 |10
3 | 4 5 | 6 |
DFS Example
source
vertex
d f
1 |12 8 |11 13|
2 | 7 9 |10
3 | 4 5 | 6 |
DFS Example
source
vertex
d f
1 |12 8 |11 13|
2 | 7 9 |10
3 | 4 5 | 6 14|
DFS Example
source
vertex
d f
1 |12 8 |11 13|
2 | 7 9 |10
3 | 4 5 | 6 14|15
DFS Example
source
vertex
d f
1 |12 8 |11 13|16
2 | 7 9 |10
3 | 4 5 | 6 14|15
DFS: Kinds of edges
● DFS introduces an important distinction
among edges in the original graph:
■ Tree edge: encounter new (white) vertex
○ The tree edges form a spanning forest
○ Can tree edges form cycles? Why or why not?
DFS Example
source
vertex
d f
1 |12 8 |11 13|16
2 | 7 9 |10
3 | 4 5 | 6 14|15
Tree edges
DFS: Kinds of edges
● DFS introduces an important distinction
among edges in the original graph:
■ Tree edge: encounter new (white) vertex
■ Back edge: from descendent to ancestor
○ Encounter a grey vertex (grey to grey)
DFS Example
source
vertex
d f
1 |12 8 |11 13|16
2 | 7 9 |10
3 | 4 5 | 6 14|15
2 | 7 9 |10
3 | 4 5 | 6 14|15
2 | 7 9 |10
3 | 4 5 | 6 14|15