Menu
CoddyTech

Strongly Connected Components

困难图python iconjava iconcpp iconc iconjs icon+10

有向图包含 n 个节点,编号从 0 到 n-1,以及一个 edges 列表,其中 [from, to] 表示一条从节点 from 到节点 to 的边。

强连通分量是由一组节点组成的最大集合,其中每个节点都可以沿着边到达其他任意节点。每个节点恰好属于一个分量,不在任何环上的节点单独构成一个分量。返回强连通分量的数量。

函数

countSCC(n: integer, edges: integer-2d-array) → integer
ninteger
节点数
edgesinteger-2d-array
有向边,每条边表示为 [from, to]
返回值integer
强连通分量的数量

约束条件

  • 2 ≤ n ≤ 104
  • 1 ≤ edges.length ≤ 5000
  • edges[i] = [from, to],其中 0 ≤ from, to < n 且 from ≠ to
  • 没有边会出现两次。

示例

输入
n = 6edges = [[0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [4, 3], [5, 4]]
输出
3
解释
节点 0、1 和 2 构成一个循环,因此它们可以相互到达。节点 3 和 4 指向彼此。节点 5 可以到达节点 4,但没有路径返回节点 5,因此它是独立的:共有 3 个连通分量。
challenge icon

进阶

要让整个图成为一个强连通分量,至少需要添加多少条边?

重置代码
def countSCC(n, edges):
    # 在这里编写代码

测试 #1

测试 #2

参数

n = 6
edges = [[0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [4, 3], [5, 4]]

预期输出

3