我已经尝试了几个小时,试图弄清楚如何实现Topsort的实际DFS部分,但是没有运气,而且我的Foreach部分一直出现错误。我的代码如下:
unction dfs(i, at, visited, ordering, graph) {
visited[at] = true; //Set node as visited
let edges = graph[at];
edges.forEach(edge => {
if (!visited[edge])
i = dfs(i, edge.to, visited, ordering, graph);
});
ordering[i] = at; //Place node
return i - 1; //Decrement index
}
function topsort(graph) {
let n = graph.length;
let visited = []; //Tracks whether node has been visited
for (a = 0; a < n; a++) {
visited[a] = null; //Initialize all nodes as null and unvisited
};
let ordering = []; //Array holds final topological order
let i = n - 1; //Insertion position of the next element in topo order. Insertions begin in the back which is why i = n-1
for (at = 0; at < n; at++) { //Iterate over nodes
if (!visited[at]) { //If a node has not been visited, initiate DFS
i = dfs(i, at, visited, ordering, graph)
};
}
return ordering;
}
let graph = [
[1],
[0, 4, 5],
[3, 4, 5],
[2, 6],
[1, 2],
[1, 2, 6],
[3, 5],
[],
];
let top = topsort(graph);
console.log(top);
运行以下链接中的代码:https://repl.it/@Stylebender/Topological-Sort#index.js
任何人都可以给我一些指示怎么做吗?