You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于结合回溯与Kahn排序的有向无环图全拓扑排序解决方案的时间复杂度咨询

Is the time complexity of finding all topological sorts via backtracking + Kahn's algorithm O(V!)?

Great observation! You're absolutely correct that the worst-case time complexity of this backtracking-based approach to find all topological sorts in a Directed Acyclic Graph (DAG) is O(V!), where V is the total number of vertices. Let me break down the reasoning to confirm this:

How the Algorithm Works

First, a quick recap of the approach:

  • It leverages Kahn's algorithm's core idea of tracking vertex in-degrees to identify valid starting points (vertices with in-degree 0).
  • For each valid starting vertex, it uses backtracking:
    1. Adds the vertex to the current topological sequence.
    2. Temporarily reduces the in-degree of the vertex's neighbors (if any).
    3. Recursively explores all valid sequences from the remaining vertices.
    4. Backtracks to restore the original in-degrees and remove the vertex from the current sequence.

Worst-Case Scenario: Isolated Vertices

The worst case occurs when the DAG consists of V isolated vertices (no edges connecting any nodes). In this scenario, every permutation of the vertices is a valid topological sort—and there are exactly V! such permutations.

Let’s break down the recursion tree for this case:

  • Level 1: V choices of vertices to pick as the first element of the sequence.
  • Level 2: For each choice from Level 1, V-1 remaining choices for the second element.
  • This pattern continues until the final level, where only 1 choice remains.

Each recursive call here does minimal work: since there are no edges, we skip updating neighbor in-degrees entirely. The primary cost comes from generating each of the V! permutations. While the exact number of operations is O(V * V!) (each permutation has V elements), the dominant term is V!, so we simplify the asymptotic complexity to O(V!).

Non-Worst-Case Scenarios

For DAGs with edges, the number of valid topological sorts is always less than V!:

  • A linear chain DAG (e.g., 1 → 2 → 3 → ... → V) has only 1 valid topological sort, leading to a time complexity of O(V + E) (matching Kahn's algorithm's standard complexity).
  • DAGs with some branching will have more sorts than a chain but far fewer than V!.

In all cases, the isolated vertex scenario is the upper bound, as it maximizes the number of valid sequences the algorithm must generate.

Your analysis is spot-on—this approach’s worst-case time complexity is indeed O(V!).

内容的提问来源于stack exchange,提问作者Shilpi Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:12:43