Created
May 18, 2018 05:05
-
-
Save zerobias/d403a52ee7dc19e28d60ace64ca8c3b9 to your computer and use it in GitHub Desktop.
Topological sort
This file contains hidden or 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
function toposortDFS(edges, begin){ | |
const inEdges = new Map() | |
const outEdges = new Map() | |
const vertices = new Set() | |
const result = new Set() | |
for (const [edge, dep] of edges) { | |
vertices.add(edge) | |
vertices.add(dep) | |
} | |
for (const vertex of vertices) { | |
outEdges.set(vertex, new Set()) | |
inEdges.set(vertex, new Set()) | |
} | |
for (const [edge, dep] of edges) { | |
outEdges.get(edge).add(dep) | |
inEdges.get(dep).add(edge) | |
} | |
function visit(vertex){ | |
if (inEdges.get(vertex).size > 0) return | |
result.add(vertex) | |
for (const outVertex of outEdges.get(vertex)) { | |
inEdges.get(outVertex).delete(vertex) | |
visit(outVertex) | |
} | |
} | |
visit(begin); | |
return [...result] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment