SorryToPerson logo
返回
算法2026-04-15·6 分钟

算法知识库:拓扑排序实现

拓扑排序的 JavaScript/TypeScript 实现,适用于有向无环图的依赖关系处理。

拓扑排序实现

1. 拓扑排序简介

  • 适用于有向无环图(DAG)。
  • 用于任务调度、依赖解析。
  • 输出一个线性序列,满足所有边的方向约束。

2. 入度统计实现

ts
type Graph = Record<string, string[]>;

function topologicalSort(graph: Graph): string[] {
  // 时间复杂度: O(V + E),空间复杂度: O(V + E) (V为顶点数,E为边数)
  const indegree: Record<string, number> = {};
  const queue: string[] = [];
  const result: string[] = [];

  Object.keys(graph).forEach((node) => {
    indegree[node] = indegree[node] ?? 0;
    for (const neighbor of graph[node]) {
      indegree[neighbor] = (indegree[neighbor] ?? 0) + 1;
    }
  });

  for (const node of Object.keys(indegree)) {
    if (indegree[node] === 0) queue.push(node);
  }

  while (queue.length) {
    const node = queue.shift()!;
    result.push(node);
    for (const neighbor of graph[node] ?? []) {
      indegree[neighbor] -= 1;
      if (indegree[neighbor] === 0) queue.push(neighbor);
    }
  }

  return result.length === Object.keys(indegree).length ? result : [];
}

3. 实现要点

  • 若图存在环,则拓扑排序返回空结果。
  • 入度队列法适合大多数场景。
  • 可用于构建依赖关系、课程表和任务调度。
算法拓扑排序JavaScript