08-27-周三_17-09-29
This commit is contained in:
35
node_modules/graphlibrary/lib/alg/topsort.js
generated
vendored
Normal file
35
node_modules/graphlibrary/lib/alg/topsort.js
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
const _ = require('../lodash')
|
||||
|
||||
module.exports = topsort
|
||||
topsort.CycleException = CycleException
|
||||
|
||||
function topsort (g) {
|
||||
const visited = {}
|
||||
const stack = {}
|
||||
const results = []
|
||||
|
||||
function visit (node) {
|
||||
if (_.has(stack, node)) {
|
||||
throw new CycleException()
|
||||
}
|
||||
|
||||
if (!_.has(visited, node)) {
|
||||
stack[node] = true
|
||||
visited[node] = true
|
||||
_.each(g.predecessors(node), visit)
|
||||
delete stack[node]
|
||||
results.push(node)
|
||||
}
|
||||
}
|
||||
|
||||
_.each(g.sinks(), visit)
|
||||
|
||||
if (_.size(visited) !== g.nodeCount()) {
|
||||
throw new CycleException()
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
function CycleException () {}
|
||||
CycleException.prototype = new Error() // must be an instance of Error to pass testing
|
Reference in New Issue
Block a user