Graph Traversal
Graph Traversal
Mahmuda Naznin
CSE 103
Graph Traversal Algorithm
2
Two basic traversal
algorithms
Two basic graph traversal algorithms:
– Depth-first-search (DFS)
» After visit node v, DFS strategy proceeds along
a path from v as deeply into the graph as
possible before backing up
– Breadth-first-search (BFS)
» After visit node v, BFS strategy visits every
node adjacent to v before visiting any other
nodes
3
Depth-first search (DFS)
From a given node v, it first visits itself. Then, recursively
visit its unvisited neighbours one by one.
DFS can be defined recursively as follows.
DFS strategy looks similar to pre-order of Tree.
Algorithm dfs(v)
print v;
mark v as visited;
for (each unvisited node u adjacent to v)
dfs(u);
4
DFS example
Start from v3
1
v3
2
v2 v2
v1 v3
x x x 3 4
v1 v4
v
x x v5
4
5
G v5
5
Breadth-first search (BFS)
6
Algorithm for BFS
Algorithm bfs(v)
q.createQueue();
q.enqueue(v);
mark v as visited;
while(!q.isEmpty()) {
w = q.dequeue();
for (each unvisited node u adjacent to w) {
q.enqueue(u);
mark u as visited;
}
}
7
BFS example
Start from v5 Visit Queue
(front to
1 back)
v5 v5 v5
v2 v3 empty
v1 2 3
x x x v3 v4
v3
v4
v3
v 3, v 4
v4x
v4
4
x v2 v2 v 4, v 2
v5 v2
G 5 empty
v1 v1 v1
8 empty
Spanning Tree
Given a connected undirected graph G, a
spanning tree of G is a subgraph of G that
contains all of G’s nodes and its
connecting edges to form a tree.
v2
v1 v3
v4 v5
Spannin
g tree Spanning tree is not unique!
9
Minimum Spanning Tree
Consider a connected undirected graph where
– Each node x represents a country x
– Each edge (x, y) has a number which measures the
cost of placing telephone line between country x and
country y
Problem: Connecting all countries while
minimizing the total cost(any network or road-
transportation, connectivity)
Solution: Find a spanning tree with minimum
total weight, that is, minimum spanning tree
10
Formal definition of MST
Given a connected undirected graph G.
Let T be a spanning tree of G.
cost(T) = eTweight(e) (weight on the edge)
The minimum spanning tree is a spanning
tree T which minimizes cost(T)
v2
v1 2 v3
5 Minimum
4 3 spanning
7
tree
v4
8 v5
11
Prim’s Algorithm
v2 v2
v1 2 v3 v1 2 v3
5 5 v2
4 3 4 3 v1 2 v3
7 7 5
v4 8 v5 v4 8 v5 4 3
7
Start from v5, find the Find the minimum v4 8 v5
minimum edge attach to edge attach to v3
v5 and v5 Find the minimum
edge attach v2 ,v3
v2 v1 v2 and v5
v1 2 v3 2 v3
5 5
4 3 4 3 7
7 8
v4 8 v5 v4 v5
Algorithm PrimAlgorithm(v)
Mark the node v as visited and include it in
the minimum spanning tree;
while (there are unvisited nodes) {
– find the minimum cost edge (v, u) between a
visited node v and an unvisited node u;
– mark u as visited;
– add both v and (v, u) to the minimum spanning
tree;
}
13
Acknowledgement
• Kenneth Rosen (Reading Mateial)
• Susanna Epp
• Ralph P. Grimaldi, B. V. Ramana