-
Notifications
You must be signed in to change notification settings - Fork 412
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
63 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
'use strict'; | ||
|
||
var PriorityQueue = require('../../data_structures/priority_queue'), | ||
Graph = require('../../data_structures/graph'); | ||
|
||
|
||
/** | ||
* Prim's minimum spanning tree (forest) algorithm. | ||
* Complexity: O(E * log(V)). | ||
* | ||
* @param {Graph} graph - Undirected graph. | ||
* @return {Graph} Minimum spanning tree or forest | ||
* (depending on whether input graph is connected itself). | ||
*/ | ||
var prim = function (graph) { | ||
if (graph.directed) { | ||
throw new Error('Can\'t build MST of a directed graph.'); | ||
} | ||
|
||
var mst = new Graph(false); | ||
var parent = Object.create(null); | ||
|
||
var q = new PriorityQueue(); | ||
graph.vertices.forEach(function (vertex) { | ||
q.insert(vertex, Infinity); | ||
}); | ||
|
||
/* jshint loopfunc: true */ | ||
while (!q.isEmpty()) { | ||
var top = q.extract(true); | ||
var vertex = top.item, | ||
weight = top.priority; | ||
|
||
if (parent[vertex]) { | ||
mst.addEdge(parent[vertex], vertex, weight); | ||
} | ||
else { | ||
mst.addVertex(vertex); | ||
} | ||
|
||
// Relax. | ||
graph.neighbors(vertex).forEach(function (neighbor) { | ||
var weight = graph.edge(vertex, neighbor); | ||
if (weight < q.priority(neighbor)) { | ||
q.changePriority(neighbor, weight); | ||
parent[neighbor] = vertex; | ||
} | ||
}); | ||
} | ||
|
||
return mst; | ||
}; | ||
|
||
|
||
module.exports = prim; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters