功能说明
该示例把一组包或任务按依赖关系排成执行顺序:被依赖的项排在依赖它的项之前。它先用入度统计“有多少人依赖于我”,再从入度为零的节点出发,逐步剥离已就绪的节点。若最终输出数量少于节点总数,说明存在环,即依赖关系不可能被满足。
关键代码
节点集合同时纳入图中的键与其提到的每个依赖,避免遗漏只作为依赖出现、未在图中显式列出的节点。入度在遍历边时累加。主循环从队列取出入度为零的节点加入结果,并让其每个依赖的入度减一,减到零即入队。输出长度与节点数不符时抛出错误,把环这一失效状态显式暴露而非静默返回残缺顺序。
使用注意
输出并非唯一:当多个节点同时入度为零时,谁先出队取决于队列顺序,如构建系统需要稳定结果,应对节点做确定性排序。该实现返回单一顺序,若需要并列的分层(哪些可并行)应改为按层输出。环检测只报告存在环,定位具体环需额外做后向追踪或强连通分量分析,否则使用者难以修复配置。
代码示例
export function topologicalSort(graph: ReadonlyMap<string, readonly string[]>): string[] {
const indegree = new Map<string, number>();
const nodes = new Set<string>(graph.keys());
for (const deps of graph.values()) for (const dep of deps) nodes.add(dep);
for (const node of nodes) indegree.set(node, 0);
for (const [, deps] of graph) for (const dep of deps) indegree.set(dep, (indegree.get(dep) ?? 0) + 1);
const queue: string[] = [];
for (const [node, degree] of indegree) if (degree === 0) queue.push(node);
const order: string[] = [];
while (queue.length > 0) {
const node = queue.shift() as string;
order.push(node);
for (const dep of graph.get(node) ?? []) {
const next = (indegree.get(dep) ?? 0) - 1;
indegree.set(dep, next);
if (next === 0) queue.push(dep);
}
}
if (order.length !== nodes.size) throw new Error('dependency graph contains a cycle');
return order;
}