1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| function EdgeNode (id) { this.id = id; this.afters = []; this.indegree = 0; }
function topsort (edges) { var nodes = {}; var result = []; var queue = [];
edges.forEach(function (edge) { var fromEdge = edge[0]; var fromStr = fromEdge.toString(); var fromNode;
if (!(fromNode = nodes[fromStr])) { fromNode = nodes[fromStr] = new EdgeNode(fromEdge); }
edge.forEach(function (toEdge) { if (toEdge == fromEdge) { return; }
var toEdgeStr = toEdge.toString();
if (!nodes[toEdgeStr]) { nodes[toEdgeStr] = new EdgeNode(toEdge); } nodes[toEdgeStr].indegree++; fromNode.afters.push(toEdge); }); });
var keys = Object.keys(nodes); keys.forEach(function (key) { if (nodes[key].indegree === 0) { queue.push(key); } }); while (queue.length !== 0) { let vertex = queue.shift(); result.push(nodes[vertex].id);
nodes[vertex].afters.forEach(function (after) { var afterStr = after.toString();
nodes[afterStr].indegree--; if (nodes[afterStr].indegree === 0) { queue.push(afterStr); } }); }
return result; }
var edges = [ ['two', 'three'], ['four', 'six'], ['one', 'three'], ['two', 'four'], ['six', 'nine'], ['five', 'seven'], ['five', 'eight'], ['five', 'nine'], ['seven', 'eight'], ['eight', 'nine'], ['one', 'two'], ['four', 'five'], ['four', 'six'], ['three', 'six'], ['six', 'seven'], ['three', 'four'] ]; var sorted = topsort(edges); console.log(sorted);
|