SlideShare a Scribd company logo
Minimum Spanning Tree
• What is a Minimum Spanning Tree.
• Constructing Minimum Spanning Trees.
• What is a Minimum-Cost Spanning Tree.
• Applications of Minimum Cost Spanning Trees.
• Prim’s Algorithm.
– Example.
– Implementation.
• Kruskal’s algorithm.
– Example.
– Implementation.
• Review Questions.
What is a Minimum Spanning Tree.
• Let G = (V, E) be a simple, connected, undirected graph that is not
edge-weighted.
• A spanning tree of G is a free tree (i.e., a tree with no root) with | V | -
1 edges that connects all the vertices of the graph.
• Thus a minimum spanning tree for G is a graph, T = (V’, E’) with the
following properties:
 V’ = V
 T is connected
 T is acyclic.
• A spanning tree is called a tree because every acyclic undirected
graph can be viewed as a general, unordered tree. Because the edges
are undirected, any vertex may be chosen to serve as the root of the
tree.
Constructing Minimum Spanning Trees
• Any traversal of a connected, undirected graph
visits all the vertices in that graph. The set of
edges which are traversed during a traversal
forms a spanning tree.
• For example, Fig:(b) shows the spanning tree
obtained from a breadth-first traversal starting at
vertex b.
• Similarly, Fig:(c) shows the spanning tree
obtained from a depth-first traversal starting at
vertex c.
(
a
)
Graph G
(b) Breadth-first
spanning tree of
G rooted at b
(c) Depth-first
spanning tree of
G rooted at c
What is a Minimum-Cost Spanning Tree
• For an edge-weighted , connected, undirected graph, G, the total
cost of G is the sum of the weights on all its edges.
• A minimum-cost spanning tree for G is a minimum spanning tree of
G that has the least total cost.
• Example: The graph
Has 16 spanning trees. Some are:
The graph has two minimum-cost spanning trees, each with a cost of 6:
Applications of Minimum-Cost Spanning Trees
Minimum-cost spanning trees have many applications. Some are:
• Building cable networks that join n locations with minimum cost.
• Building a road network that joins n cities with minimum cost.
• Obtaining an independent set of circuit equations for an electrical
network.
• In pattern recognition minimal spanning trees can be used to find noisy
pixels.
Prim’s Algorithm
• Prim’s algorithm finds a minimum cost spanning tree by selecting
edges from the graph one-by-one as follows:
• It starts with a tree, T, consisting of the starting vertex, x.
• Then, it adds the shortest edge emanating from x that connects T to
the rest of the graph.
• It then moves to the added vertex and repeats the process.
Consider a graph G=(V, E);
Let T be a tree consisting of only the starting vertex x;
while (T has fewer than IVI vertices)
{
find a smallest edge connecting T to G-T;
add it to T;
}
Example
Trace Prim’s algorithm starting at vertex a
:
The resulting minimum-cost spanning tree is
:
Implementation of Prim’s Algorithm.
• Prims algorithn can be implememted similar to the Dijskra’s
algorithm as shown below:
public static Graph primsAlgorithm(Graph g, Vertex start){
int n = g.getNumberOfVertices();
Entry table[] = new Entry[n];
for(int v = 0; v < n; v++)
table[v] = new Entry();
table[g.getIndex(start)].distance = 0;
PriorityQueue queue = new BinaryHeap(g.getNumberOfEdges());
queue.enqueue(new Association(new Integer(0), start));
while(!queue.isEmpty()) {
Association association = (Association)queue.dequeueMin();
Vertex v1 = (Vertex) association.getValue();
int n1 = g.getIndex(v1);
if(!table[n1].known){
table[n1].known = true;
Iterator p = v1.getEmanatingEdges();
while (p.hasNext()){
Edge edge = (Edge) p.next();
Vertex v2 = edge.getMate(v1);
int n2 = g.getIndex(v2);
Integer weight = (Integer) edge.getWeight();
int d = weight.intValue();
Implementation of Prim’s Algorithm Cont'd
if(!table[n2].known && table[n2].distance > d){
table[n2].distance = d; table[n2].predecessor = v1;
queue.enqueue(new Association(new Integer(d), v2));
}
}
}
}
GraphAsLists result = new GraphAsLists(false);
Iterator it = g.getVertices();
while (it.hasNext()){
Vertex v = (Vertex) it.next();
result.addVertex(v.getLabel());
}
it = g.getVertices();
while (it.hasNext()){
Vertex v = (Vertex) it.next();
if (v != start){
int index = g.getIndex(v);
String from = v.getLabel();
String to = table[index].predecessor.getLabel();
result.addEdge(from, to, new Integer(table[index].distance));
}
}
return result;
}
Kruskal's Algorithm.
• Kruskal’s algorithm also finds the minimum cost
spanning tree of a graph by adding edges one-by-one.
enqueue edges of G in a queue in increasing order of cost.
T =  ;
while(queue is not empty){
dequeue an edge e;
if(e does not create a cycle with edges in T)
add e to T;
}
return T;
Example for Kruskal’s Algorithm.
Trace Kruskal's algorithm in finding a minimum-cost spanning tree for the
undirected, weighted graph given below:
The minimum cost is: 24
Implementation of Kruskal's Algorithm
public static Graph kruskalsAlgorithm(Graph g){
Graph result = new GraphAsLists(false);
Iterator it = g.getVertices();
while (it.hasNext()){
Vertex v = (Vertex)it.next();
result.addVertex(v.getLabel());
}
PriorityQueue queue = new BinaryHeap(g.getNumberOfEdges());
it = g.getEdges();
while(it.hasNext()){
Edge e = (Edge) it.next();
if (e.getWeight()==null)
throw new IllegalArgumentException("Graph is not weighted");
queue.enqueue(e);
}
while (!queue.isEmpty()){
Edge e = (Edge) queue.dequeueMin();
String from = e.getFromVertex().getLabel();
String to = e.getToVertex().getLabel();
if (!result.isReachable(from, to))
result.addEdge(from,to,e.getWeight());
}
return result;
}
adds an edge only, if it
does not create a cycle
Implementation of Kruskal's Algorithm – Cont’d
public abstract class AbstractGraph implements Graph {
public boolean isReachable(String from, String to){
Vertex fromVertex = getVertex(from);
Vertex toVertex = getVertex(to);
if (fromVertex == null || toVertex==null)
throw new IllegalArgumentException("Vertex not in the graph");
PathVisitor visitor = new PathVisitor(toVertex);
this.preorderDepthFirstTraversal(visitor, fromVertex);
return visitor.isReached();
}
private class PathVisitor implements Visitor {
boolean reached = false;
Vertex target;
PathVisitor(Vertex t){target = t;}
public void visit(Object obj){
Vertex v = (Vertex) obj;
if (v.equals(target)) reached = true;
}
public boolean isDone(){return reached;}
boolean isReached(){return reached;}
}
}
Prim’s and Kruskal’s Algorithms
Note: It is not necessary that Prim's and Kruskal's algorithm generate the same minimum-cost
spanning tree.
For example for the graph:
Kruskal's algorithm (that imposes an ordering on edges with equal weights) results
in the following minimum cost spanning tree:
The same tree is generated by Prim's algorithm if the start vertex is any of: A, B, or
D; however if the start vertex is C the minimum cost spanning tree is:
Review Questions
1. Find the breadth-first spanning tree and depth-first spanning tree of the
graph GA shown above.
2. For the graph GB shown above, trace the execution of Prim's algorithm as it
finds the minimum-cost spanning tree of the graph starting from vertex a.
3. Repeat question 2 above using Kruskal's algorithm.
GB

More Related Content

PPTX
uva-201026072839.pptxvcvczcvzvcxbxcvbcxvbvcxbcx
PPTX
11L_2024_DSCS_EN_Trees2_Prim_Kraskal.pptx
PPTX
GRAPH APPLICATION - MINIMUM SPANNING TREE (MST)
PPT
Minimum Spanning Tree
PPTX
Minimum Spanning Tree.pptx
PPTX
Minimum spanning tree
PPTX
Ram minimum spanning tree
PPT
Minimum spanning tree
uva-201026072839.pptxvcvczcvzvcxbxcvbcxvbvcxbcx
11L_2024_DSCS_EN_Trees2_Prim_Kraskal.pptx
GRAPH APPLICATION - MINIMUM SPANNING TREE (MST)
Minimum Spanning Tree
Minimum Spanning Tree.pptx
Minimum spanning tree
Ram minimum spanning tree
Minimum spanning tree

Similar to Unit27_MinimumSpanningTree.ppt data structure programming (20)

PPTX
APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...
PPT
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
PPTX
prim's and kruskal's algorithm
PPTX
_A C program for Prim's Minimum Spanning Tree (MST) algorithm. The program is...
PPTX
Greedy technique - Algorithm design techniques using data structures
PPTX
7. Spanning trees
PPTX
Prim's Algorithm Presentation for prims algorithm (1).pptx
PDF
Skiena algorithm 2007 lecture13 minimum spanning trees
PDF
Topological Sort
PPT
Unit 5 graphs minimum spanning trees
PPT
Greedy Approach in Design Analysis and Algorithms
PDF
Ijciras1101
PPT
Greedy Algorithms Chapter for new students 4.ppt
PPT
Spanning trees
PPTX
UNIT II - Graph Algorithms techniques.pptx
PPT
Prim's Algorithm on minimum spanning tree
PPTX
Minimum Spanning Tree (Data Structure and Algorithm)
PPTX
Minimum spanning tree
APznzaZLM_MVouyxM4cxHPJR5BC-TAxTWqhQJ2EywQQuXStxJTDoGkHdsKEQGd4Vo7BS3Q1npCOMV...
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
prim's and kruskal's algorithm
_A C program for Prim's Minimum Spanning Tree (MST) algorithm. The program is...
Greedy technique - Algorithm design techniques using data structures
7. Spanning trees
Prim's Algorithm Presentation for prims algorithm (1).pptx
Skiena algorithm 2007 lecture13 minimum spanning trees
Topological Sort
Unit 5 graphs minimum spanning trees
Greedy Approach in Design Analysis and Algorithms
Ijciras1101
Greedy Algorithms Chapter for new students 4.ppt
Spanning trees
UNIT II - Graph Algorithms techniques.pptx
Prim's Algorithm on minimum spanning tree
Minimum Spanning Tree (Data Structure and Algorithm)
Minimum spanning tree
Ad

Recently uploaded (20)

PPTX
Sustainable Sites - Green Building Construction
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Construction Project Organization Group 2.pptx
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPT
Mechanical Engineering MATERIALS Selection
PPTX
OOP with Java - Java Introduction (Basics)
PDF
composite construction of structures.pdf
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
PPT on Performance Review to get promotions
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Sustainable Sites - Green Building Construction
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Construction Project Organization Group 2.pptx
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Mechanical Engineering MATERIALS Selection
OOP with Java - Java Introduction (Basics)
composite construction of structures.pdf
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPT on Performance Review to get promotions
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
additive manufacturing of ss316l using mig welding
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Ad

Unit27_MinimumSpanningTree.ppt data structure programming

  • 1. Minimum Spanning Tree • What is a Minimum Spanning Tree. • Constructing Minimum Spanning Trees. • What is a Minimum-Cost Spanning Tree. • Applications of Minimum Cost Spanning Trees. • Prim’s Algorithm. – Example. – Implementation. • Kruskal’s algorithm. – Example. – Implementation. • Review Questions.
  • 2. What is a Minimum Spanning Tree. • Let G = (V, E) be a simple, connected, undirected graph that is not edge-weighted. • A spanning tree of G is a free tree (i.e., a tree with no root) with | V | - 1 edges that connects all the vertices of the graph. • Thus a minimum spanning tree for G is a graph, T = (V’, E’) with the following properties:  V’ = V  T is connected  T is acyclic. • A spanning tree is called a tree because every acyclic undirected graph can be viewed as a general, unordered tree. Because the edges are undirected, any vertex may be chosen to serve as the root of the tree.
  • 3. Constructing Minimum Spanning Trees • Any traversal of a connected, undirected graph visits all the vertices in that graph. The set of edges which are traversed during a traversal forms a spanning tree. • For example, Fig:(b) shows the spanning tree obtained from a breadth-first traversal starting at vertex b. • Similarly, Fig:(c) shows the spanning tree obtained from a depth-first traversal starting at vertex c. ( a ) Graph G (b) Breadth-first spanning tree of G rooted at b (c) Depth-first spanning tree of G rooted at c
  • 4. What is a Minimum-Cost Spanning Tree • For an edge-weighted , connected, undirected graph, G, the total cost of G is the sum of the weights on all its edges. • A minimum-cost spanning tree for G is a minimum spanning tree of G that has the least total cost. • Example: The graph Has 16 spanning trees. Some are: The graph has two minimum-cost spanning trees, each with a cost of 6:
  • 5. Applications of Minimum-Cost Spanning Trees Minimum-cost spanning trees have many applications. Some are: • Building cable networks that join n locations with minimum cost. • Building a road network that joins n cities with minimum cost. • Obtaining an independent set of circuit equations for an electrical network. • In pattern recognition minimal spanning trees can be used to find noisy pixels.
  • 6. Prim’s Algorithm • Prim’s algorithm finds a minimum cost spanning tree by selecting edges from the graph one-by-one as follows: • It starts with a tree, T, consisting of the starting vertex, x. • Then, it adds the shortest edge emanating from x that connects T to the rest of the graph. • It then moves to the added vertex and repeats the process. Consider a graph G=(V, E); Let T be a tree consisting of only the starting vertex x; while (T has fewer than IVI vertices) { find a smallest edge connecting T to G-T; add it to T; }
  • 7. Example Trace Prim’s algorithm starting at vertex a : The resulting minimum-cost spanning tree is :
  • 8. Implementation of Prim’s Algorithm. • Prims algorithn can be implememted similar to the Dijskra’s algorithm as shown below: public static Graph primsAlgorithm(Graph g, Vertex start){ int n = g.getNumberOfVertices(); Entry table[] = new Entry[n]; for(int v = 0; v < n; v++) table[v] = new Entry(); table[g.getIndex(start)].distance = 0; PriorityQueue queue = new BinaryHeap(g.getNumberOfEdges()); queue.enqueue(new Association(new Integer(0), start)); while(!queue.isEmpty()) { Association association = (Association)queue.dequeueMin(); Vertex v1 = (Vertex) association.getValue(); int n1 = g.getIndex(v1); if(!table[n1].known){ table[n1].known = true; Iterator p = v1.getEmanatingEdges(); while (p.hasNext()){ Edge edge = (Edge) p.next(); Vertex v2 = edge.getMate(v1); int n2 = g.getIndex(v2); Integer weight = (Integer) edge.getWeight(); int d = weight.intValue();
  • 9. Implementation of Prim’s Algorithm Cont'd if(!table[n2].known && table[n2].distance > d){ table[n2].distance = d; table[n2].predecessor = v1; queue.enqueue(new Association(new Integer(d), v2)); } } } } GraphAsLists result = new GraphAsLists(false); Iterator it = g.getVertices(); while (it.hasNext()){ Vertex v = (Vertex) it.next(); result.addVertex(v.getLabel()); } it = g.getVertices(); while (it.hasNext()){ Vertex v = (Vertex) it.next(); if (v != start){ int index = g.getIndex(v); String from = v.getLabel(); String to = table[index].predecessor.getLabel(); result.addEdge(from, to, new Integer(table[index].distance)); } } return result; }
  • 10. Kruskal's Algorithm. • Kruskal’s algorithm also finds the minimum cost spanning tree of a graph by adding edges one-by-one. enqueue edges of G in a queue in increasing order of cost. T =  ; while(queue is not empty){ dequeue an edge e; if(e does not create a cycle with edges in T) add e to T; } return T;
  • 11. Example for Kruskal’s Algorithm. Trace Kruskal's algorithm in finding a minimum-cost spanning tree for the undirected, weighted graph given below: The minimum cost is: 24
  • 12. Implementation of Kruskal's Algorithm public static Graph kruskalsAlgorithm(Graph g){ Graph result = new GraphAsLists(false); Iterator it = g.getVertices(); while (it.hasNext()){ Vertex v = (Vertex)it.next(); result.addVertex(v.getLabel()); } PriorityQueue queue = new BinaryHeap(g.getNumberOfEdges()); it = g.getEdges(); while(it.hasNext()){ Edge e = (Edge) it.next(); if (e.getWeight()==null) throw new IllegalArgumentException("Graph is not weighted"); queue.enqueue(e); } while (!queue.isEmpty()){ Edge e = (Edge) queue.dequeueMin(); String from = e.getFromVertex().getLabel(); String to = e.getToVertex().getLabel(); if (!result.isReachable(from, to)) result.addEdge(from,to,e.getWeight()); } return result; } adds an edge only, if it does not create a cycle
  • 13. Implementation of Kruskal's Algorithm – Cont’d public abstract class AbstractGraph implements Graph { public boolean isReachable(String from, String to){ Vertex fromVertex = getVertex(from); Vertex toVertex = getVertex(to); if (fromVertex == null || toVertex==null) throw new IllegalArgumentException("Vertex not in the graph"); PathVisitor visitor = new PathVisitor(toVertex); this.preorderDepthFirstTraversal(visitor, fromVertex); return visitor.isReached(); } private class PathVisitor implements Visitor { boolean reached = false; Vertex target; PathVisitor(Vertex t){target = t;} public void visit(Object obj){ Vertex v = (Vertex) obj; if (v.equals(target)) reached = true; } public boolean isDone(){return reached;} boolean isReached(){return reached;} } }
  • 14. Prim’s and Kruskal’s Algorithms Note: It is not necessary that Prim's and Kruskal's algorithm generate the same minimum-cost spanning tree. For example for the graph: Kruskal's algorithm (that imposes an ordering on edges with equal weights) results in the following minimum cost spanning tree: The same tree is generated by Prim's algorithm if the start vertex is any of: A, B, or D; however if the start vertex is C the minimum cost spanning tree is:
  • 15. Review Questions 1. Find the breadth-first spanning tree and depth-first spanning tree of the graph GA shown above. 2. For the graph GB shown above, trace the execution of Prim's algorithm as it finds the minimum-cost spanning tree of the graph starting from vertex a. 3. Repeat question 2 above using Kruskal's algorithm. GB