Last active
October 2, 2023 22:40
-
-
Save ChristopherBilg/79e39744f4e8c546b92096fc2179d71a to your computer and use it in GitHub Desktop.
Simple minimum spanning tree (MST) implementation in JS; note: the cycle checking function works for this small graph, but will need to be implemented in larger graphs
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
const vertices = ['a', 'b', 'c', 'd']; | |
const edges = [ | |
{ | |
starting: 'c', | |
ending: 'd', | |
weight: 500, | |
}, | |
{ | |
starting: 'a', | |
ending: 'b', | |
weight: 1, | |
}, | |
{ | |
starting: 'b', | |
ending: 'c', | |
weight: 1, | |
}, | |
{ | |
starting: 'c', | |
ending: 'd', | |
weight: 1, | |
} | |
]; | |
// Note: I didn't actually implement the cycle checking algorithm, | |
// but functionally it's the same for the given graph G. | |
const doesGraphContainAtleastOneCycle = (arr) => { | |
return false; | |
}; | |
const findMinimumSpanningTree = () => { | |
// O(E log E) | |
let sortedEdges = edges.sort((a, b) => { | |
if (a.weight < b.weight) return -1; | |
else if (a.weight > b.weight) return 1; | |
else return 0; | |
}); | |
const minimumSpanningTree = []; | |
while (sortedEdges.length > 0 && minimumSpanningTree.length < (vertices.length - 1)) { | |
const tempEdge = sortedEdges.shift(); | |
// If a cycle exists with the new edge, then don't push it into the MST array | |
const tempMST = [...minimumSpanningTree, tempEdge]; | |
if (doesGraphContainAtleastOneCycle(tempMST)) continue; | |
minimumSpanningTree.push(tempEdge); | |
} | |
return minimumSpanningTree.length === (vertices.length - 1) | |
? minimumSpanningTree | |
: null; | |
}; | |
const result = findMinimumSpanningTree(); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment