|
| 1 | +/* eslint-disable no-unused-vars */ |
| 2 | +import {Graph} from '../../../data-structures/graph/graph'; |
| 3 | +import {GraphVertex} from '../../../data-structures/graph/graphVertex'; |
| 4 | +import {GraphConfig} from '../../../data-structures/graph/graphConfig'; |
| 5 | +import {depthFirstSearch} from '../depth-first-search/depthFirstSearch'; |
| 6 | + |
| 7 | +/** |
| 8 | + * |
| 9 | + * |
| 10 | + * @export |
| 11 | + * @param {Graph} graph |
| 12 | + * @param {GraphConfig} config |
| 13 | + * @return {GraphVertex[]} |
| 14 | + */ |
| 15 | +export function topological( |
| 16 | + graph: Graph, |
| 17 | + config: GraphConfig = null, |
| 18 | +): GraphVertex[] { |
| 19 | + if (!graph) { |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + // A set of unvisited vertices |
| 24 | + const unvisited = {}; |
| 25 | + graph.getVertices().forEach((vertex) => { |
| 26 | + unvisited[vertex.getKey()] = vertex; |
| 27 | + }); |
| 28 | + |
| 29 | + // A set of visited vertices |
| 30 | + const visited = {}; |
| 31 | + |
| 32 | + // An array, which behaves like a stack (to hold the order) |
| 33 | + const stack = []; |
| 34 | + |
| 35 | + config = config || ({} as GraphConfig); |
| 36 | + |
| 37 | + // Visit only unvisited vertices |
| 38 | + config.allowEnterVertex = |
| 39 | + config.allowEnterVertex || |
| 40 | + ((vertex: GraphVertex) => { |
| 41 | + return !visited[vertex.getKey()]; |
| 42 | + }); |
| 43 | + |
| 44 | + config.enterVertex = |
| 45 | + config.enterVertex || |
| 46 | + ((vertex: GraphVertex) => { |
| 47 | + // Remove a vertex from the unvisited set |
| 48 | + delete unvisited[vertex.getKey()]; |
| 49 | + |
| 50 | + // Mark a vertex as visited |
| 51 | + visited[vertex.getKey()] = vertex; |
| 52 | + }); |
| 53 | + |
| 54 | + /* Push the vertex onto the stack, |
| 55 | + * when all of the vertex neighbors have been visited */ |
| 56 | + config.leaveVertex = |
| 57 | + config.leaveVertex || |
| 58 | + ((vertex: GraphVertex) => { |
| 59 | + // TODO: Replace with an actual stack implementation |
| 60 | + stack.push(vertex); |
| 61 | + }); |
| 62 | + |
| 63 | + while (Object.keys(unvisited).length) { |
| 64 | + const startVertexKey = Object.keys(unvisited)[0]; |
| 65 | + const startVertex = unvisited[startVertexKey]; |
| 66 | + |
| 67 | + depthFirstSearch(graph, startVertex, config); |
| 68 | + } |
| 69 | + |
| 70 | + return stack.reverse(); |
| 71 | +} |
0 commit comments