Last active
January 15, 2019 12:38
-
-
Save robbywashere-zz/d57aa53b37fb15dae3712c01faf186cc to your computer and use it in GitHub Desktop.
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
class Graph { | |
constructor(){ | |
this.nodes = {}; | |
} | |
addNode(n){ | |
if (!this.nodes[n]) this.nodes[n] = []; | |
} | |
addDirEdge(a,b){ | |
this.nodes[a].push(b); | |
} | |
} | |
let g = new Graph(); | |
g.addNode("A"); | |
g.addNode("B"); | |
g.addNode("C"); | |
g.addNode("D"); | |
g.addNode("E"); | |
g.addNode("F"); | |
g.addNode("G"); | |
g.addDirEdge("A", "C"); | |
g.addDirEdge("A", "B"); | |
g.addDirEdge("A", "D"); | |
g.addDirEdge("C", "D"); | |
g.addDirEdge("D", "E"); | |
g.addDirEdge("E", "F"); | |
g.addDirEdge("B", "G"); | |
function topoSort(graph){ | |
let stack = []; | |
let explored = new Set(); | |
for (let node of Object.keys(graph.nodes)){ | |
if (!explored.has(node)){ | |
function ts(n){ | |
explored.add(n); | |
graph.nodes[n].forEach(nextNode=>{ | |
if (!explored.has(nextNode)) ts(nextNode); | |
}) | |
stack.push(n); | |
} | |
ts(node) | |
} | |
} | |
while (stack.length) console.log(stack.pop()) | |
} | |
topoSort(g); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment