Graphs, DFS, BFS, SP, ST Algorithms
Graphs, DFS, BFS, SP, ST Algorithms
Algorithm Analysis
Graph Algorithms
3
2 4
1 15
9 4 6
1 13
4
12 5
3 5
The Shortest Path Problem
Input: A weighted directed graph G=(V, E), where V={1, 2, …, n};
Output: The distance from vertex 1 to every other vertex in G;
1. X={1}; YV-{1}; [1]0;
2. for y2 to n
3. if y is adjacent to 1 then [y]length[1, y];
4. else [y];
5. end if;
6. end for;
7. for j1 to n-1
8. Let yY be such that [y] is minimum;
9. XX{y}; //add vertex y to X
10. YY-{y}; //delete vertex y from Y
11. for each edge (y, w)
12. if wY and [y]+length[y, w]<[w] then
13. [w][y]+length[y, w];
14. end for;
15. end for;
The Shortest Path Problem
What’s the performance of the
DIJKSTRA algorithm?
Time Complexity?
The Shortest Path Problem
Given a directed graph G with nonnegative weights
on its edges and a source vertex s, Algorithm
DIJKSTRA finds the length of the distance from s to
every other vertex in (n2) time.
The Shortest Path Problem
Write codes to implement the Dijkstra algorithm.
Minimum Cost Spanning
Trees (Kruskal’s Algorithm)
Let G=(V, E) be a connected undirected graph with
weights on its edges.
6 9 6
1 7
4
2 13
3 5
Minimum Cost Spanning
Trees (Kruskal’s Algorithm)
Write codes to implement the Kruskal algorithm.
Graph Traversal
In some cases, what is important is that the vertices
are visited in a systematic order, regardless of the
input graph. Usually, there are two methods of graph
traversal:
Depth-first search
Breadth-first search
Depth-First Search
Let G=(V, E) be a directed or undirected graph.
d a i
c b g h
e f j
Depth-First Search
When the search is complete, if all vertices are reachable
from the start vertex, a spanning tree called the depth-
first search spanning tree is constructed whose edges are
those inspected in the forward direction, i.e., when
exploring unvisited vertices.
As a result of the traversal, the edges of an undirected
graph G are classified into the following two types:
Tree edges: edges in the depth-first search tree.
Back edges: all other edges.
Depth-First Search
Input: An undirected graph G=(V, E);
Output: Preordering of the vertices in the corresponding depth-first
search tree.
1. predfn0;
2. for each vertex vV
3. Mark v unvisited;
4. end for;
5. for each vertex vV
6. if v is marked unvisited then dfs(v);
7. end for;
dfs(v)
1. Mark v visited;
2. predfnpredfn+1;
3. for each edge (v, w)E
4. if w is marked unvisited then dfs(w);
5. end for;
Depth-First Search
Write codes to implement the Depth-First Search
on graph.
Breadth-First Search
When we visit a vertex v, we next visit all vertices
adjacent to v.
d a i
c b g h
e f j
Homework
9.1
9.3
9.5a
9.9
9.15a (only Kruskal algorithm)
9.18
9.20
9.21