graphs II
graphs II
DFS Algorithm
Input: A graph G (by adjacency lists) and a root vertex r
Output: An ordering of the vertices in the connected component of G
containing r .
DFS(Ex, r ): Explore first indepth before backtracking
1 1 1 1
2 2 2
3 3 4
1 1 1
1
2 2 7 2 7
2
3 4 5 3 4 5 3 4 5
3 4 5
6 6 6 8
BFS Algorithm
Input: A graph G (by adjacency lists) and a root vertex r
Output: An ordering of the vertices in the connected component of G
containing r .
▶ Start at initial vertex (root) r .
▶ Visit all vertices adjacent to the root r (put them on a queue).
▶ Repeatedly visit the neighbours of visited vertices.
▶ Stop when there are no new vertices to visit.
1 1 1 1
2 3 2 3 2 3
4 5 4 5 6
1
2 3
4 5 6
7 8
(ESCI) Graph Algorithms 4 / 10
Breadth First Search
Exploring graphs
BFS Algorithm
Input: A graph G (by adjacency lists) and a root vertex r
Output: An ordering of the vertices in the connected component of G
containing r .
▶ Start at initial vertex (root) r .
▶ Visit all vertices adjacent to the root r (put them on a queue).
▶ Repeatedly visit the neighbours of visited vertices.
▶ Stop when there are no new vertices to visit.
BFS Algorithm
Input: A graph G (by adjacency lists) and a root vertex r
Output: An ordering of the vertices in the connected component of G
containing r .
▶ Start at initial vertex (root) r .
▶ Visit all vertices adjacent to the root r (put them on a queue).
▶ Repeatedly visit the neighbours of visited vertices.
▶ Stop when there are no new vertices to visit.
Theorem
G is a bipartite graph if and only if it contains no odd cycles.
Theorem
G is a bipartite graph if and only if it contains no odd cycles.
2 2
3 7 73
2 2
9 9
1 5 3 1 5 3 w (H) = 24
1 6 8 1 6 8
4 4
MST Problem
Given an edge–weighted graph G = (V , E , w ) find a spanning tree of G with
minimum weight.
(ESCI) Graph Algorithms 7 / 10
Kruskal Algorithm
Input: An edge–weighted graph G .
Ouput: A forest of minimum weight (in terms of its edges)
▶ Sort the edges in non–decreasing weights {e1 , . . . , em }
▶ Initialize F0 = {∅}.
▶ for i from 1 to n do
if Fi−1 ∪ ei is acyclic then Fi = Fi−1 ∪ ei else Fi = Fi−1 .
▶ Return Fm .
103 103
1 1
1 1
1 1
103 1 103 1
1 1
1 1
103 103
3 3
10 10
(ESCI) Graph Algorithms 8 / 10
Kruskal Algorithm
Input: An edge–weighted graph G .
Ouput: A forest of minimum weight (in terms of its edges)
▶ Sort the edges in non–decreasing weights {e1 , . . . , em }
▶ Initialize F0 = {∅}.
▶ for i from 1 to n do
if Fi−1 ∪ ei is acyclic then Fi = Fi−1 ∪ ei else Fi = Fi−1 .
▶ Return Fm .
a
7
8
5 b c
7
9 15 5
d e
6 9
8 11
f g