Skip to content

Commit 95aeee7

Browse files
committed
Merge pull request algorithm-visualizer#35 from TornjV/feature/mst
MST and Prim's Algorithm
2 parents da6ef40 + e4a7efd commit 95aeee7

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed

algorithm/category.json

+6
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@
1010
"topological_sort": "Topological-Sort"
1111
}
1212
},
13+
"mst": {
14+
"name": "Minimum Spanning Tree",
15+
"list": {
16+
"prim": "Prim's Algorithm"
17+
}
18+
},
1319
"search": {
1420
"name": "Search",
1521
"list": {

algorithm/mst/prim/desc.json

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"Prim's Algorithm": "Greedy algorithm that finds a minimum spanning tree for a weighted undirected graph.",
3+
"Applications": [
4+
],
5+
"Complexity": {
6+
"time": "worst O(|V|<sup>2</sup>)"
7+
},
8+
"References": [
9+
"<a href='https://en.wikipedia.org/wiki/Prim%27s_algorithm'>Wikipedia</a>"
10+
],
11+
"files": {
12+
"normal": "Finds minimum spanning tree of a given graph."
13+
}
14+
}

algorithm/mst/prim/normal/code.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
function prim(){
2+
// Finds a tree so that there exists a path between
3+
// every two nodes while keeping the cost minimal
4+
var minD, minI, minJ, sum=0, D=[];
5+
for(var i = 0; i < G.length; i++) D.push(0);
6+
D[0] = 1; // First node is visited
7+
for(var k = 0; k < G.length-1; k++){ // Searching for k edges
8+
minD = Infinity;
9+
for(i = 0; i< G.length; i++)
10+
if(D[i]) // First node in an edge must be visited
11+
for(var j = 0; j < G.length; j++)
12+
if(!D[j] && G[i][j]){
13+
tracer._visit(i, j);
14+
// Second node must not be visited and must be connected to first node
15+
if(G[i][j] < minD){
16+
// Searching for cheapest edge which satisfies requirements
17+
minD = G[i][j];
18+
minI = i;
19+
minJ = j;
20+
}
21+
tracer._leave(i, j);
22+
}
23+
tracer._visit(minI, minJ);
24+
D[minJ] = 1; // Visit second node and insert it into or tree
25+
sum += G[minI][minJ];
26+
}
27+
tracer._print("The sum of all edges is: " + sum);
28+
}
29+
30+
tracer._pace(500);
31+
tracer._print("nodes that belong to minimum spanning tree are: ");
32+
prim();

algorithm/mst/prim/normal/data.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
var tracer = new WeightedUndirectedGraphTracer();
2+
/*var G = [ // G[i][j] indicates the weight of the path from the i-th node to the j-th node
3+
[0, 3, 0, 1, 0],
4+
[5, 0, 1, 2, 4],
5+
[1, 0, 0, 2, 0],
6+
[0, 2, 0, 0, 1],
7+
[0, 1, 3, 0, 0]
8+
];*/
9+
var G = WeightedUndirectedGraph.random(10, .4, 1, 9);
10+
tracer._setData(G);

0 commit comments

Comments
 (0)