SlideShare a Scribd company logo
1 of 76
Download to read offline
Algorithms
Topological Sort
Strongly connected components
Minimum Spanning Trees
Example DAG
Watch
Socks
Shoes
Undershorts
Pants
Belt Tie
Shirt
Jacket
a DAG implies an
ordering on events
Example DAG
Watch
Socks
Shoes
Undershorts
Pants
Belt Tie
Shirt
Jacket
In a complex DAG, it
can be hard to find a
schedule that obeys
all the constraints.
Directed Acyclic Graphs
ā— A directed acyclic graph or DAG is a directed
graph with no directed cycles:
DFS and DAGs
ā— Theorem: a directed graph G is acyclic iff a DFS of G
yields no back edges:
ā–  => if G is acyclic, will be no back edges
ā—‹ Trivial: a back edge implies a cycle
ā–  <= if no back edges, G is acyclic
ā—‹ Proof by contradiction: G has a cycle a back edge
ļµ Let v be the vertex on the cycle first discovered, and u be the
predecessor of v on the cycle
ļµ When v discovered, whole cycle is white
ļµ Must visit everything reachable from v before returning from DFS-
Visit()
ļµ So path from u v is gray gray, thus (u, v) is a back edge
Topological Sort
Topological Sort
ā— For a directed acyclic graph G = (V,E)
ā— A topological sort is an ordering of all of Gā€™s
vertices v1, v2, ā€¦, vn such that...
ā— vertex u comes before vertex v if edge (u, v) G
Formally: for every edge (vi,vk) in E, i<k.
Visually: all arrows are pointing to the right
Topological sort
ā— There are often many possible topological
sorts of a given DAG
ā— Topological orders for this DAG :
ā—‹ 1,2,5,4,3,6,7
ā—‹ 2,1,5,4,7,3,6
ā—‹ 2,5,1,4,7,3,6
ā—‹ Etc.
ā— Each topological order is a feasible schedule.
1
4
76
3 5
2
Topological Sorts for Cyclic
Graphs?
Impossible!
1 2
3
ā€¢ If v and w are two vertices on a cycle, there
exist paths from v to w and from w to v.
ā€¢ Any ordering will contradict one of these paths
A Topological Sort Algorithm
Topological-Sort()
{
1. Call DFS to compute finish time f[v] for
each vertex
2. As each vertex is finished, insert it onto
the front of a linked list
3. Return the linked list of vertices
}
ā— Time: O(V+E)
ā— Correctness: need to prove that
(u,v) G f[u]>f[v]
Correctness of Topological Sort
ā— Lemma: (u,v) G f[u] > f[v]
ā–  When (u,v) is explored, u is gray, consider the
following cases:
1. v is gray (u,v) is back edge. Canā€™t happen, if G is
a DAG.
2. v if white v becomes descendent of u
f[v] < f[u]
(since must finish v before backtracking and
finishing u)
3. v is black v already finished f[v] < f[u]
Strongly Connected Directed graphs
ā— Every pair of vertices are reachable from each other
a
b
d
c
e
f
g
Strongly-Connected
Graph G is strongly connected if, for every u
and v in V, there is some path from u to v and
some path from v to u.
Strongly
Connected
Not Strongly
Connected
Strongly-Connected Components
A strongly connected component of a graph is a
maximal subset of nodes (along with their
associated edges) that is strongly connected.
Nodes share a strongly connected component
if they are inter-reachable.
Strongly Connected Components
a
b
d
c
e
f
g
{ a , c , g }
{ f , d , e , b }
Reduced Component Graph of
Strongly Connected Components
a
b
d
c
e
f
g
{ a , c , g }
{ f , d , e , b }
ā— Component graph GSCC=(VSCC, ESCC): one
vertex for each component
ā–  (u, v) ESCC if there exists at least one directed
edge from the corresponding components
Strongly-Connected Components
Strongly-Connected-Components(G)
1. call DFS(G) to compute finishing times f[u] for each
vertex u.
2. compute GT
3. call DFS(GT), but in the main loop of DFS, consider
the vertices in order of decreasing f[u]
4. output the vertices of each tree in the depth-first forest
of step 3 as a separate strongly connected component.
The graph GT is the transpose of G, which is visualized
by reversing the arrows on the digraph.
Runtime
Lines 1 and 3 are (E+V) due to DFS
Line 2 involves creating an adjacency list or
matrix, and it is also O(E+V)
Line 4 is constant time
So, SCC(G) is (E+V)
Strongly connected components
ā— Definition: the strongly connected components
(SCC) C1, ā€¦, Ck of a directed graph G = (V,E)
are the largest disjoint sub-graphs (no common
vertices or edges) such that for any two vertices
u and v in Ci, there is a path from u to v and from
v to u.
ā— Equivalence classes of the binary path(u,v)
relation, denoted by u ~ v.
ā— Applications: networking, communications.
ā— Problem: compute the strongly connected
components of G in linear time Ī˜(|V|+|E|).
Example: strongly connected
components
d
b
f
e
a
c
g
h
Example: strongly connected
components
d
b
f
e
a
c
g
h
Example: transpose graph GT
d
b
f
e
a
c
g
h
d
b
f
e
a
c
g
h
G
GT
Example: SCC graph
C
C
C
C
d
b
f
e
a
c
g
h
Graph Traversals
Graph Traversals
ā€¢Both take time: O(V+E)
Graph Searching ???
ā— Graph as state space (node = state, edge = action)
ā— For example, game trees, mazes, ...
ā— BFS and DFS each search the state space for a best move. If
the search is exhaustive they will find the same solution, but if
there is a time limit and the search space is large...
ā— DFS explores a few possible moves, looking at the effects far
in the future
ā— BFS explores many solutions but only sees effects in the near
future (often finds shorter solutions)
Minimum Spanning Trees
Problem: Laying Telephone Wire
Central office
Wiring: NaĆÆve Approach
Central office
Expensive!
Wiring: Better Approach
Central office
Minimize the total length of wire connecting the customers
Minimum Spanning Tree (MST)
ā€¢ it is a tree (i.e., it is acyclic)
ā€¢ it covers all the vertices V
ā€“ contains |V| - 1 edges
ā€¢ the total cost associated with tree edges is the
minimum among all possible spanning trees
ā€¢ not necessarily unique
A minimum spanning tree is a subgraph of an
undirected weighted graph G, such that
How Can We Generate a MST?
a
c
e
d
b
2
45
9
6
4
5
5
a
c
e
d
b
2
45
9
6
4
5
5
Minimum Spanning Tree: Prim's
Algorithm
ā— Prim's algorithm for finding an MST is a
greedy algorithm.
ā— Start by selecting an arbitrary vertex, include it
into the current MST.
ā— Grow the current MST by inserting into it the
vertex closest to one of the vertices already in
current MST.
Primā€˜s Algorithm
1. All vertices are marked as not visited
2. Any vertex v you like is chosen as starting vertex and
is marked as visited (define a cluster C)
3. The smallest- weighted edge e = (v,u), which connects
one vertex v inside the cluster C with another vertex u
outside of C, is chosen and is added to the MST.
4. The process is repeated until a spanning tree is formed
C
FE
A B
D
5
64
3
4
2
1 2
3
2
C
FE
A B
D
5
64
3
4
2
1 2
3
2
C
FE
A B
D
5
64
3
4
2
1 2
3
2
We could delete these edges
because of Dijkstraā€žs label D[u] for
each vertex outside of the cluster
C
FE
A B
D
3
4
2
1 2
3
2
C
FE
A B
D
3
2
1 2
3
2
C
FE
A B
D
3
2
1 2
2
3
C
FE
A B
D
3
2
1 2
2
C
FE
A B
D
3
2
1 2
2
C
FE
A B
D
3
2
1 2
2
minimum- spanning tree
Primā€™s algorithm
a
c
e
d
b
2
45
9
6
4
5
5
d b c a
4 5 5
Vertex Parent
e -
b e
c e
d e
The MST initially consists of the vertex e, and we update
the distances and parent for its adjacent vertices
Vertex Parent
e -
b -
c -
d -
d b c ae
0
Primā€™s algorithm
a
c
e
d
b
2
45
9
6
4
5
5
a c b
2 4 5
Vertex Parent
e -
b e
c d
d e
a d
d b c a
4 5 5
Vertex Parent
e -
b e
c e
d e
Primā€™s algorithm
a
c
e
d
b
2
45
9
6
4
5
5
c b
4 5
Vertex Parent
e -
b e
c d
d e
a d
a c b
2 4 5
Vertex Parent
e -
b e
c d
d e
a d
Primā€™s algorithm
a
c
e
d
b
2
45
9
6
4
5
5
b
5
Vertex Parent
e -
b e
c d
d e
a d
c b
4 5
Vertex Parent
e -
b e
c d
d e
a d
Primā€™s algorithm
Vertex Parent
e -
b e
c d
d e
a d
a
c
e
d
b
2
45
9
6
4
5
5
The final minimum spanning tree
b
5
Vertex Parent
e -
b e
c d
d e
a d
Running time of Primā€™s algorithm
(without heaps)
Initialization of priority queue (array): O(|V|)
Update loop: |V| calls
ā€¢ Choosing vertex with minimum cost edge: O(|V|)
ā€¢ Updating distance values of unconnected
vertices: each edge is considered only once
during entire execution, for a total of O(|E|)
updates
Overall cost without heaps:
When heaps are used, apply same analysis as for
Dijkstraā€Ÿs algorithm (p.469) (good exercise)
O(|E| + |V| 2)
Primā€™s Algorithm Invariant
ā— At each step, we add the edge (u,v) s.t. the weight of
(u,v) is minimum among all edges where u is in the
tree and v is not in the tree
ā— Each step maintains a minimum spanning tree of the
vertices that have been included thus far
ā— When all vertices have been included, we have a MST
for the graph!
Correctness of Primā€™s
ā— This algorithm adds n-1 edges without creating a cycle, so
clearly it creates a spanning tree of any connected graph
(you should be able to prove this).
But is this a minimum spanning tree?
Suppose it wasn't.
ā— There must be point at which it fails, and in particular there
must a single edge whose insertion first prevented the
spanning tree from being a minimum spanning tree.
Correctness of Primā€™s
ā€¢ Let V' be the vertices incident with edges in S
ā€¢ Let T be a MST of G containing all edges in S, but not (x,y).
ā€¢ Let G be a connected,
undirected graph
ā€¢ Let S be the set of
edges chosen by Primā€Ÿs
algorithm before
choosing an errorful
edge (x,y)
x
y
Correctness of Primā€™s
x
y
v
w
ā€¢ There is exactly one edge on this cycle with exactly
one vertex in Vā€™, call this edge (v,w)
ā€¢ Edge (x,y) is not in T, so
there must be a path in
T from x to y since T is
connected.
ā€¢ Inserting edge (x,y) into
T will create a cycle
Correctness of Primā€™s
ā— Since Primā€™s chose (x,y) over (v,w), w(v,w) >= w(x,y).
ā— We could form a new spanning tree Tā€™ by swapping (x,y)
for (v,w) in T (prove this is a spanning tree).
ā— w(Tā€™) is clearly no greater than w(T)
ā— But that means Tā€™ is a MST
ā— And yet it contains all the edges in S, and also (x,y)
...Contradiction
Another Approach
a
c
e
d
b
2
45
9
6
4
5
5
ā€¢ Create a forest of trees from the vertices
ā€¢ Repeatedly merge trees by adding ā€œsafe edgesā€
until only one tree remains
ā€¢ A ā€œsafe edgeā€ is an edge of minimum weight which
does not create a cycle
forest: {a}, {b}, {c}, {d}, {e}
Kruskalā€™s algorithm
Initialization
a. Create a set for each vertex v V
b. Initialize the set of ā€œsafe edgesā€ A
comprising the MST to the empty set
c. Sort edges by increasing weight
a
c
e
d
b
2
45
9
6
4
5
5
F = {a}, {b}, {c}, {d}, {e}
A =
E = {(a,d), (c,d), (d,e), (a,c),
(b,e), (c,e), (b,d), (a,b)}
Kruskalā€™s algorithm
For each edge (u,v) E in increasing order
while more than one set remains:
If u and v, belong to different sets U and V
a. add edge (u,v) to the safe edge set
A = A {(u,v)}
b. merge the sets U and V
F = F - U - V + (U V)
Return A
ā— Running time bounded by sorting (or findMin)
ā— O(|E|log|E|), or equivalently, O(|E|log|V|) (why???)
Kruskalā€™s algorithm
E = {(a,d), (c,d), (d,e), (a,c),
(b,e), (c,e), (b,d), (a,b)}
Forest
{a}, {b}, {c}, {d}, {e}
{a,d}, {b}, {c}, {e}
{a,d,c}, {b}, {e}
{a,d,c,e}, {b}
{a,d,c,e,b}
A
{(a,d)}
{(a,d), (c,d)}
{(a,d), (c,d), (d,e)}
{(a,d), (c,d), (d,e), (b,e)}
a
c
e
d
b
2
45
9
6
4
5
5
ā— After each iteration, every tree in the forest is a MST of the
vertices it connects
ā— Algorithm terminates when all vertices are connected into one
tree
Kruskalā€™s Algorithm Invariant
Correctness of Kruskalā€™s
ā— This algorithm adds n-1 edges without creating a cycle, so
clearly it creates a spanning tree of any connected graph
(you should be able to prove this).
But is this a minimum spanning tree?
Suppose it wasn't.
ā— There must be point at which it fails, and in particular there
must a single edge whose insertion first prevented the
spanning tree from being a minimum spanning tree.
Correctness of Kruskalā€™s
ā— Let e be this first errorful edge.
ā— Let K be the Kruskal spanning tree
ā— Let S be the set of edges chosen by Kruskalā€™s algorithm
before choosing e
ā— Let T be a MST containing all edges in S, but not e.
K T
S
e
Correctness of Kruskalā€™s
Proof (by contradiction):
ā— Assume there exists some
edge eā€™ in T - S, w(eā€™) < w(e)
ā— Kruskalā€™s must have
considered eā€™ before e
K T
S
e
Lemma: w(eā€™) >= w(e) for all edges eā€™ in T - S
ā€¢ However, since eā€™ is not in K (why??), it must have
been discarded because it caused a cycle with some of
the other edges in S.
ā€¢ But eā€™ + S is a subgraph of T, which means it cannot
form a cycle ...Contradiction
Correctness of Kruskalā€™s
ā— Inserting edge e into T will create a cycle
ā— There must be an edge on this cycle which is not in K
(why??). Call this edge eā€™
ā— eā€™ must be in T - S, so (by our lemma) w(eā€™) >= w(e)
ā— We could form a new spanning tree Tā€™ by swapping e for eā€™ in
T (prove this is a spanning tree).
ā— w(Tā€™) is clearly no greater than w(T)
ā— But that means Tā€™ is a MST
ā— And yet it contains all the edges in S, and also e
...Contradiction
Greedy Approach
ā— Like Dijkstraā€™s algorithm, both Primā€™s and Kruskalā€™s
algorithms are greedy algorithms
ā— The greedy approach works for the MST problem;
however, it does not work for many other problems!
Thatā€™s All!

More Related Content

What's hot

Prims and kruskal algorithms
Prims and kruskal algorithmsPrims and kruskal algorithms
Prims and kruskal algorithmsSaga Valsalan
Ā 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsDrishti Bhalla
Ā 
Minimum Spanning Tree
Minimum Spanning TreeMinimum Spanning Tree
Minimum Spanning Treezhaokatherine
Ā 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsNikhil Sharma
Ā 
Kruskal Algorithm
Kruskal AlgorithmKruskal Algorithm
Kruskal AlgorithmBhavik Vashi
Ā 
Dijkstraā€™S Algorithm
Dijkstraā€™S AlgorithmDijkstraā€™S Algorithm
Dijkstraā€™S Algorithmami_01
Ā 
Algorithms Lecture 7: Graph Algorithms
Algorithms Lecture 7: Graph AlgorithmsAlgorithms Lecture 7: Graph Algorithms
Algorithms Lecture 7: Graph AlgorithmsMohamed Loey
Ā 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Shuvongkor Barman
Ā 
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)Mohanlal Sukhadia University (MLSU)
Ā 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning treeHinal Lunagariya
Ā 
Shortest path algorithm
Shortest path algorithmShortest path algorithm
Shortest path algorithmsana younas
Ā 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structureAbrish06
Ā 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Treesagar yadav
Ā 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTanzeela_Hussain
Ā 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy AlgorithmsAmrinder Arora
Ā 
Hash table
Hash tableHash table
Hash tableRajendran
Ā 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting AlgorithmsPranay Neema
Ā 

What's hot (20)

Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
Ā 
Dijkstra's Algorithm
Dijkstra's Algorithm Dijkstra's Algorithm
Dijkstra's Algorithm
Ā 
Prims and kruskal algorithms
Prims and kruskal algorithmsPrims and kruskal algorithms
Prims and kruskal algorithms
Ā 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
Ā 
Minimum Spanning Tree
Minimum Spanning TreeMinimum Spanning Tree
Minimum Spanning Tree
Ā 
Shortest Path in Graph
Shortest Path in GraphShortest Path in Graph
Shortest Path in Graph
Ā 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
Ā 
Kruskal Algorithm
Kruskal AlgorithmKruskal Algorithm
Kruskal Algorithm
Ā 
Dijkstraā€™S Algorithm
Dijkstraā€™S AlgorithmDijkstraā€™S Algorithm
Dijkstraā€™S Algorithm
Ā 
Algorithms Lecture 7: Graph Algorithms
Algorithms Lecture 7: Graph AlgorithmsAlgorithms Lecture 7: Graph Algorithms
Algorithms Lecture 7: Graph Algorithms
Ā 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
Ā 
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
Shortest path (Dijkistra's Algorithm) & Spanning Tree (Prim's Algorithm)
Ā 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
Ā 
Shortest path algorithm
Shortest path algorithmShortest path algorithm
Shortest path algorithm
Ā 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
Ā 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Ā 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive Parsing
Ā 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
Ā 
Hash table
Hash tableHash table
Hash table
Ā 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Ā 

Similar to Topological Sort

graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docxgraphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docxwhittemorelucilla
Ā 
Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8Traian Rebedea
Ā 
topological_sort_strongly Connected Components
topological_sort_strongly Connected Componentstopological_sort_strongly Connected Components
topological_sort_strongly Connected ComponentsJahidulIslam47153
Ā 
Secure Domination in graphs
Secure Domination in graphsSecure Domination in graphs
Secure Domination in graphsMahesh Gadhwal
Ā 
minimum spanning trees Algorithm
minimum spanning trees Algorithm minimum spanning trees Algorithm
minimum spanning trees Algorithm sachin varun
Ā 
Chap10 slides
Chap10 slidesChap10 slides
Chap10 slidesHJ DS
Ā 
Algorithm to count number of disjoint paths
Algorithm to count number of disjoint pathsAlgorithm to count number of disjoint paths
Algorithm to count number of disjoint pathsSujith Jay Nair
Ā 
09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdfPrasanna David
Ā 
APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...
APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...
APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...KUSHDHIRRA2111026030
Ā 

Similar to Topological Sort (20)

Optimisation random graph presentation
Optimisation random graph presentationOptimisation random graph presentation
Optimisation random graph presentation
Ā 
Unit ix graph
Unit   ix    graph Unit   ix    graph
Unit ix graph
Ā 
Unit 9 graph
Unit   9 graphUnit   9 graph
Unit 9 graph
Ā 
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docxgraphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
graphin-c1.pnggraphin-c1.txt1 22 3 83 44 5.docx
Ā 
Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8Algorithm Design and Complexity - Course 8
Algorithm Design and Complexity - Course 8
Ā 
topological_sort_strongly Connected Components
topological_sort_strongly Connected Componentstopological_sort_strongly Connected Components
topological_sort_strongly Connected Components
Ā 
Secure Domination in graphs
Secure Domination in graphsSecure Domination in graphs
Secure Domination in graphs
Ā 
Graphs
GraphsGraphs
Graphs
Ā 
minimum spanning trees Algorithm
minimum spanning trees Algorithm minimum spanning trees Algorithm
minimum spanning trees Algorithm
Ā 
Algorithms Design Exam Help
Algorithms Design Exam HelpAlgorithms Design Exam Help
Algorithms Design Exam Help
Ā 
Chap10 slides
Chap10 slidesChap10 slides
Chap10 slides
Ā 
Algorithms Design Assignment Help
Algorithms Design Assignment HelpAlgorithms Design Assignment Help
Algorithms Design Assignment Help
Ā 
Unit ii-ppt
Unit ii-pptUnit ii-ppt
Unit ii-ppt
Ā 
Algorithm to count number of disjoint paths
Algorithm to count number of disjoint pathsAlgorithm to count number of disjoint paths
Algorithm to count number of disjoint paths
Ā 
Unit 2: All
Unit 2: AllUnit 2: All
Unit 2: All
Ā 
09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf
Ā 
Graphs
GraphsGraphs
Graphs
Ā 
APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...
APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...
APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...
Ā 
6. Graphs
6. Graphs6. Graphs
6. Graphs
Ā 
Introduction to Graph Theory
Introduction to Graph TheoryIntroduction to Graph Theory
Introduction to Graph Theory
Ā 

More from Dr Sandeep Kumar Poonia

An improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmAn improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmDr Sandeep Kumar Poonia
Ā 
Modified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmModified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmDr Sandeep Kumar Poonia
Ā 
Enhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmEnhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmDr Sandeep Kumar Poonia
Ā 
Memetic search in differential evolution algorithm
Memetic search in differential evolution algorithmMemetic search in differential evolution algorithm
Memetic search in differential evolution algorithmDr Sandeep Kumar Poonia
Ā 
Improved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmImproved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmDr Sandeep Kumar Poonia
Ā 
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmComparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmDr Sandeep Kumar Poonia
Ā 
A novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmA novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmDr Sandeep Kumar Poonia
Ā 
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsMultiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsDr Sandeep Kumar Poonia
Ā 
Sunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmSunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmDr Sandeep Kumar Poonia
Ā 
New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm Dr Sandeep Kumar Poonia
Ā 
Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Dr Sandeep Kumar Poonia
Ā 
Database aggregation using metadata
Database aggregation using metadataDatabase aggregation using metadata
Database aggregation using metadataDr Sandeep Kumar Poonia
Ā 
Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Dr Sandeep Kumar Poonia
Ā 

More from Dr Sandeep Kumar Poonia (20)

Soft computing
Soft computingSoft computing
Soft computing
Ā 
An improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmAn improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithm
Ā 
Modified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmModified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithm
Ā 
Enhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmEnhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithm
Ā 
RMABC
RMABCRMABC
RMABC
Ā 
Memetic search in differential evolution algorithm
Memetic search in differential evolution algorithmMemetic search in differential evolution algorithm
Memetic search in differential evolution algorithm
Ā 
Improved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmImproved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithm
Ā 
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmComparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
Ā 
A novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmA novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithm
Ā 
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsMultiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
Ā 
Sunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmSunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithm
Ā 
New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm
Ā 
A new approach of program slicing
A new approach of program slicingA new approach of program slicing
A new approach of program slicing
Ā 
Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...
Ā 
Enhanced abc algo for tsp
Enhanced abc algo for tspEnhanced abc algo for tsp
Enhanced abc algo for tsp
Ā 
Database aggregation using metadata
Database aggregation using metadataDatabase aggregation using metadata
Database aggregation using metadata
Ā 
Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...
Ā 
Lecture28 tsp
Lecture28 tspLecture28 tsp
Lecture28 tsp
Ā 
Lecture27 linear programming
Lecture27 linear programmingLecture27 linear programming
Lecture27 linear programming
Ā 
Lecture26
Lecture26Lecture26
Lecture26
Ā 

Recently uploaded

How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
Ā 
Visit to a blind student's schoolšŸ§‘ā€šŸ¦ÆšŸ§‘ā€šŸ¦Æ(community medicine)
Visit to a blind student's schoolšŸ§‘ā€šŸ¦ÆšŸ§‘ā€šŸ¦Æ(community medicine)Visit to a blind student's schoolšŸ§‘ā€šŸ¦ÆšŸ§‘ā€šŸ¦Æ(community medicine)
Visit to a blind student's schoolšŸ§‘ā€šŸ¦ÆšŸ§‘ā€šŸ¦Æ(community medicine)lakshayb543
Ā 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
Ā 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
Ā 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
Ā 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
Ā 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A BeƱa
Ā 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
Ā 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
Ā 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
Ā 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
Ā 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
Ā 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
Ā 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
Ā 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
Ā 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
Ā 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
Ā 

Recently uploaded (20)

prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
Ā 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Ā 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
Ā 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
Ā 
Visit to a blind student's schoolšŸ§‘ā€šŸ¦ÆšŸ§‘ā€šŸ¦Æ(community medicine)
Visit to a blind student's schoolšŸ§‘ā€šŸ¦ÆšŸ§‘ā€šŸ¦Æ(community medicine)Visit to a blind student's schoolšŸ§‘ā€šŸ¦ÆšŸ§‘ā€šŸ¦Æ(community medicine)
Visit to a blind student's schoolšŸ§‘ā€šŸ¦ÆšŸ§‘ā€šŸ¦Æ(community medicine)
Ā 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
Ā 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
Ā 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
Ā 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
Ā 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
Ā 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Ā 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
Ā 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Ā 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
Ā 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Ā 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
Ā 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
Ā 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Ā 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
Ā 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
Ā 

Topological Sort

  • 1. Algorithms Topological Sort Strongly connected components Minimum Spanning Trees
  • 3. Example DAG Watch Socks Shoes Undershorts Pants Belt Tie Shirt Jacket In a complex DAG, it can be hard to find a schedule that obeys all the constraints.
  • 4. Directed Acyclic Graphs ā— A directed acyclic graph or DAG is a directed graph with no directed cycles:
  • 5. DFS and DAGs ā— Theorem: a directed graph G is acyclic iff a DFS of G yields no back edges: ā–  => if G is acyclic, will be no back edges ā—‹ Trivial: a back edge implies a cycle ā–  <= if no back edges, G is acyclic ā—‹ Proof by contradiction: G has a cycle a back edge ļµ Let v be the vertex on the cycle first discovered, and u be the predecessor of v on the cycle ļµ When v discovered, whole cycle is white ļµ Must visit everything reachable from v before returning from DFS- Visit() ļµ So path from u v is gray gray, thus (u, v) is a back edge
  • 7. Topological Sort ā— For a directed acyclic graph G = (V,E) ā— A topological sort is an ordering of all of Gā€™s vertices v1, v2, ā€¦, vn such that... ā— vertex u comes before vertex v if edge (u, v) G Formally: for every edge (vi,vk) in E, i<k. Visually: all arrows are pointing to the right
  • 8. Topological sort ā— There are often many possible topological sorts of a given DAG ā— Topological orders for this DAG : ā—‹ 1,2,5,4,3,6,7 ā—‹ 2,1,5,4,7,3,6 ā—‹ 2,5,1,4,7,3,6 ā—‹ Etc. ā— Each topological order is a feasible schedule. 1 4 76 3 5 2
  • 9. Topological Sorts for Cyclic Graphs? Impossible! 1 2 3 ā€¢ If v and w are two vertices on a cycle, there exist paths from v to w and from w to v. ā€¢ Any ordering will contradict one of these paths
  • 10. A Topological Sort Algorithm Topological-Sort() { 1. Call DFS to compute finish time f[v] for each vertex 2. As each vertex is finished, insert it onto the front of a linked list 3. Return the linked list of vertices } ā— Time: O(V+E) ā— Correctness: need to prove that (u,v) G f[u]>f[v]
  • 11. Correctness of Topological Sort ā— Lemma: (u,v) G f[u] > f[v] ā–  When (u,v) is explored, u is gray, consider the following cases: 1. v is gray (u,v) is back edge. Canā€™t happen, if G is a DAG. 2. v if white v becomes descendent of u f[v] < f[u] (since must finish v before backtracking and finishing u) 3. v is black v already finished f[v] < f[u]
  • 12. Strongly Connected Directed graphs ā— Every pair of vertices are reachable from each other a b d c e f g
  • 13. Strongly-Connected Graph G is strongly connected if, for every u and v in V, there is some path from u to v and some path from v to u. Strongly Connected Not Strongly Connected
  • 14. Strongly-Connected Components A strongly connected component of a graph is a maximal subset of nodes (along with their associated edges) that is strongly connected. Nodes share a strongly connected component if they are inter-reachable.
  • 15. Strongly Connected Components a b d c e f g { a , c , g } { f , d , e , b }
  • 16. Reduced Component Graph of Strongly Connected Components a b d c e f g { a , c , g } { f , d , e , b } ā— Component graph GSCC=(VSCC, ESCC): one vertex for each component ā–  (u, v) ESCC if there exists at least one directed edge from the corresponding components
  • 17. Strongly-Connected Components Strongly-Connected-Components(G) 1. call DFS(G) to compute finishing times f[u] for each vertex u. 2. compute GT 3. call DFS(GT), but in the main loop of DFS, consider the vertices in order of decreasing f[u] 4. output the vertices of each tree in the depth-first forest of step 3 as a separate strongly connected component. The graph GT is the transpose of G, which is visualized by reversing the arrows on the digraph.
  • 18. Runtime Lines 1 and 3 are (E+V) due to DFS Line 2 involves creating an adjacency list or matrix, and it is also O(E+V) Line 4 is constant time So, SCC(G) is (E+V)
  • 19. Strongly connected components ā— Definition: the strongly connected components (SCC) C1, ā€¦, Ck of a directed graph G = (V,E) are the largest disjoint sub-graphs (no common vertices or edges) such that for any two vertices u and v in Ci, there is a path from u to v and from v to u. ā— Equivalence classes of the binary path(u,v) relation, denoted by u ~ v. ā— Applications: networking, communications. ā— Problem: compute the strongly connected components of G in linear time Ī˜(|V|+|E|).
  • 22. Example: transpose graph GT d b f e a c g h d b f e a c g h G GT
  • 26. Graph Searching ??? ā— Graph as state space (node = state, edge = action) ā— For example, game trees, mazes, ... ā— BFS and DFS each search the state space for a best move. If the search is exhaustive they will find the same solution, but if there is a time limit and the search space is large... ā— DFS explores a few possible moves, looking at the effects far in the future ā— BFS explores many solutions but only sees effects in the near future (often finds shorter solutions)
  • 28. Problem: Laying Telephone Wire Central office
  • 30. Wiring: Better Approach Central office Minimize the total length of wire connecting the customers
  • 31. Minimum Spanning Tree (MST) ā€¢ it is a tree (i.e., it is acyclic) ā€¢ it covers all the vertices V ā€“ contains |V| - 1 edges ā€¢ the total cost associated with tree edges is the minimum among all possible spanning trees ā€¢ not necessarily unique A minimum spanning tree is a subgraph of an undirected weighted graph G, such that
  • 32. How Can We Generate a MST? a c e d b 2 45 9 6 4 5 5 a c e d b 2 45 9 6 4 5 5
  • 33. Minimum Spanning Tree: Prim's Algorithm ā— Prim's algorithm for finding an MST is a greedy algorithm. ā— Start by selecting an arbitrary vertex, include it into the current MST. ā— Grow the current MST by inserting into it the vertex closest to one of the vertices already in current MST.
  • 34.
  • 35. Primā€˜s Algorithm 1. All vertices are marked as not visited 2. Any vertex v you like is chosen as starting vertex and is marked as visited (define a cluster C) 3. The smallest- weighted edge e = (v,u), which connects one vertex v inside the cluster C with another vertex u outside of C, is chosen and is added to the MST. 4. The process is repeated until a spanning tree is formed
  • 38. C FE A B D 5 64 3 4 2 1 2 3 2 We could delete these edges because of Dijkstraā€žs label D[u] for each vertex outside of the cluster
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55. Primā€™s algorithm a c e d b 2 45 9 6 4 5 5 d b c a 4 5 5 Vertex Parent e - b e c e d e The MST initially consists of the vertex e, and we update the distances and parent for its adjacent vertices Vertex Parent e - b - c - d - d b c ae 0
  • 56. Primā€™s algorithm a c e d b 2 45 9 6 4 5 5 a c b 2 4 5 Vertex Parent e - b e c d d e a d d b c a 4 5 5 Vertex Parent e - b e c e d e
  • 57. Primā€™s algorithm a c e d b 2 45 9 6 4 5 5 c b 4 5 Vertex Parent e - b e c d d e a d a c b 2 4 5 Vertex Parent e - b e c d d e a d
  • 58. Primā€™s algorithm a c e d b 2 45 9 6 4 5 5 b 5 Vertex Parent e - b e c d d e a d c b 4 5 Vertex Parent e - b e c d d e a d
  • 59. Primā€™s algorithm Vertex Parent e - b e c d d e a d a c e d b 2 45 9 6 4 5 5 The final minimum spanning tree b 5 Vertex Parent e - b e c d d e a d
  • 60. Running time of Primā€™s algorithm (without heaps) Initialization of priority queue (array): O(|V|) Update loop: |V| calls ā€¢ Choosing vertex with minimum cost edge: O(|V|) ā€¢ Updating distance values of unconnected vertices: each edge is considered only once during entire execution, for a total of O(|E|) updates Overall cost without heaps: When heaps are used, apply same analysis as for Dijkstraā€Ÿs algorithm (p.469) (good exercise) O(|E| + |V| 2)
  • 61. Primā€™s Algorithm Invariant ā— At each step, we add the edge (u,v) s.t. the weight of (u,v) is minimum among all edges where u is in the tree and v is not in the tree ā— Each step maintains a minimum spanning tree of the vertices that have been included thus far ā— When all vertices have been included, we have a MST for the graph!
  • 62. Correctness of Primā€™s ā— This algorithm adds n-1 edges without creating a cycle, so clearly it creates a spanning tree of any connected graph (you should be able to prove this). But is this a minimum spanning tree? Suppose it wasn't. ā— There must be point at which it fails, and in particular there must a single edge whose insertion first prevented the spanning tree from being a minimum spanning tree.
  • 63. Correctness of Primā€™s ā€¢ Let V' be the vertices incident with edges in S ā€¢ Let T be a MST of G containing all edges in S, but not (x,y). ā€¢ Let G be a connected, undirected graph ā€¢ Let S be the set of edges chosen by Primā€Ÿs algorithm before choosing an errorful edge (x,y) x y
  • 64. Correctness of Primā€™s x y v w ā€¢ There is exactly one edge on this cycle with exactly one vertex in Vā€™, call this edge (v,w) ā€¢ Edge (x,y) is not in T, so there must be a path in T from x to y since T is connected. ā€¢ Inserting edge (x,y) into T will create a cycle
  • 65. Correctness of Primā€™s ā— Since Primā€™s chose (x,y) over (v,w), w(v,w) >= w(x,y). ā— We could form a new spanning tree Tā€™ by swapping (x,y) for (v,w) in T (prove this is a spanning tree). ā— w(Tā€™) is clearly no greater than w(T) ā— But that means Tā€™ is a MST ā— And yet it contains all the edges in S, and also (x,y) ...Contradiction
  • 66. Another Approach a c e d b 2 45 9 6 4 5 5 ā€¢ Create a forest of trees from the vertices ā€¢ Repeatedly merge trees by adding ā€œsafe edgesā€ until only one tree remains ā€¢ A ā€œsafe edgeā€ is an edge of minimum weight which does not create a cycle forest: {a}, {b}, {c}, {d}, {e}
  • 67. Kruskalā€™s algorithm Initialization a. Create a set for each vertex v V b. Initialize the set of ā€œsafe edgesā€ A comprising the MST to the empty set c. Sort edges by increasing weight a c e d b 2 45 9 6 4 5 5 F = {a}, {b}, {c}, {d}, {e} A = E = {(a,d), (c,d), (d,e), (a,c), (b,e), (c,e), (b,d), (a,b)}
  • 68. Kruskalā€™s algorithm For each edge (u,v) E in increasing order while more than one set remains: If u and v, belong to different sets U and V a. add edge (u,v) to the safe edge set A = A {(u,v)} b. merge the sets U and V F = F - U - V + (U V) Return A ā— Running time bounded by sorting (or findMin) ā— O(|E|log|E|), or equivalently, O(|E|log|V|) (why???)
  • 69. Kruskalā€™s algorithm E = {(a,d), (c,d), (d,e), (a,c), (b,e), (c,e), (b,d), (a,b)} Forest {a}, {b}, {c}, {d}, {e} {a,d}, {b}, {c}, {e} {a,d,c}, {b}, {e} {a,d,c,e}, {b} {a,d,c,e,b} A {(a,d)} {(a,d), (c,d)} {(a,d), (c,d), (d,e)} {(a,d), (c,d), (d,e), (b,e)} a c e d b 2 45 9 6 4 5 5
  • 70. ā— After each iteration, every tree in the forest is a MST of the vertices it connects ā— Algorithm terminates when all vertices are connected into one tree Kruskalā€™s Algorithm Invariant
  • 71. Correctness of Kruskalā€™s ā— This algorithm adds n-1 edges without creating a cycle, so clearly it creates a spanning tree of any connected graph (you should be able to prove this). But is this a minimum spanning tree? Suppose it wasn't. ā— There must be point at which it fails, and in particular there must a single edge whose insertion first prevented the spanning tree from being a minimum spanning tree.
  • 72. Correctness of Kruskalā€™s ā— Let e be this first errorful edge. ā— Let K be the Kruskal spanning tree ā— Let S be the set of edges chosen by Kruskalā€™s algorithm before choosing e ā— Let T be a MST containing all edges in S, but not e. K T S e
  • 73. Correctness of Kruskalā€™s Proof (by contradiction): ā— Assume there exists some edge eā€™ in T - S, w(eā€™) < w(e) ā— Kruskalā€™s must have considered eā€™ before e K T S e Lemma: w(eā€™) >= w(e) for all edges eā€™ in T - S ā€¢ However, since eā€™ is not in K (why??), it must have been discarded because it caused a cycle with some of the other edges in S. ā€¢ But eā€™ + S is a subgraph of T, which means it cannot form a cycle ...Contradiction
  • 74. Correctness of Kruskalā€™s ā— Inserting edge e into T will create a cycle ā— There must be an edge on this cycle which is not in K (why??). Call this edge eā€™ ā— eā€™ must be in T - S, so (by our lemma) w(eā€™) >= w(e) ā— We could form a new spanning tree Tā€™ by swapping e for eā€™ in T (prove this is a spanning tree). ā— w(Tā€™) is clearly no greater than w(T) ā— But that means Tā€™ is a MST ā— And yet it contains all the edges in S, and also e ...Contradiction
  • 75. Greedy Approach ā— Like Dijkstraā€™s algorithm, both Primā€™s and Kruskalā€™s algorithms are greedy algorithms ā— The greedy approach works for the MST problem; however, it does not work for many other problems!