Skip to content

Instantly share code, notes, and snippets.

@PunkSage
Last active June 17, 2016 09:42
Show Gist options
  • Save PunkSage/9b9ee6ed14abe24df86004b765c08383 to your computer and use it in GitHub Desktop.
Save PunkSage/9b9ee6ed14abe24df86004b765c08383 to your computer and use it in GitHub Desktop.
Topological sorting
var Graph = function() {
var nodes = {
'a': { id: 'a', state: 'unvisited', output: ['b','c','d']},
'b': { id: 'b', state: 'unvisited', output: ['e']},
'c': { id: 'c', state: 'unvisited', output: ['e']},
'd': { id: 'd', state: 'unvisited', output: ['f']},
'e': { id: 'e', state: 'unvisited', output: ['f']},
'f': { id: 'f', state: 'unvisited', output: ['g']},
'g': { id: 'g', state: 'unvisited', output: []}
};
var nodes = {
'a': { id: 'a', state: 'unvisited', output: ['b','c']},
'b': { id: 'b', state: 'unvisited', output: ['c']},
'c': { id: 'c', state: 'unvisited', output: []},
};
this.getNodeById = function(name) {
var result = nodes[name];
if (result) { return result } else
throw new Error('Node not found');
}
this.getAllNodes = function() {
var result = [];
for (var node in nodes) {
result.push(node);
}
return result;
}
}
function topologicalSort(graph) {
var solution = [];
for (var j = 0; j < graph.getAllNodes().length; j++) {
if (graph.getNodeById(graph.getAllNodes()[j]).state === 'unvisited') {
var startNode = graph.getNodeById(graph.getAllNodes()[j]);
var stack = [startNode];
while (stack.length > 0) {
var node = stack[stack.length - 1];
if (node.state === 'extracted') {
solution.push(stack.pop().id);
} else {
for (var i = 0; i < node.output.length; i++) {
var dest = graph.getNodeById(node.output[i]);
if (stack.indexOf(dest) > -1) {
throw new Error('Loop found');
} else
if (dest.state === 'unvisited') {
dest.state = 'visited';
stack.push(dest);
}
}
node.state = 'extracted';
}
}
}
}
return solution.reverse();
}
function regularDFS(graph, startNode) {
var solution = [];
var stack = [startNode];
while (stack.length > 0) {
var node = stack.pop();
solution.push(node.id);
node.state = 'visited';
for (var i=0; i < node.output.length; i++) {
var dest = graph.getNodeById(node.output[i]);
if (dest.state === 'unvisited') {
stack.push(dest);
}
}
}
return solution;
}
console.log('topological sort: ', topologicalSort(new Graph(),new Graph().getNodeById('a')));
console.log('regular dfs: ', regularDFS(new Graph(),new Graph().getNodeById('a')));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment