Menu
CoddyTech

Strongly Connected Components

HardGraphspython iconjava iconcpp iconc iconjs icon+10

A directed graph has n nodes, numbered 0 to n-1, and a list of edges, where [from, to] is an edge from node from to node to.

A strongly connected component is a largest group of nodes in which every node can reach every other node by following edges. Every node belongs to exactly one component, and a node on no cycle forms a component by itself. Return the number of strongly connected components.

Function

countSCC(n: integer, edges: integer-2d-array) → integer
ninteger
the number of nodes
edgesinteger-2d-array
the directed edges, each as [from, to]
Returnsinteger
the number of strongly connected components

Constraints

  • 2 ≤ n ≤ 104
  • 1 ≤ edges.length ≤ 5000
  • edges[i] = [from, to] with 0 ≤ from, to < n and from ≠ to
  • No edge appears twice.

Examples

Input
n = 6edges = [[0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [4, 3], [5, 4]]
Output
3
Explanation
Nodes 0, 1 and 2 form a loop, so they reach each other. Nodes 3 and 4 point at each other. Node 5 reaches 4, but nothing comes back to 5, so it stands alone: 3 components.
challenge icon

Follow-up

How few edges would you need to add to make the whole graph a single strongly connected component?

Reset code
def countSCC(n, edges):
    # Write code here

Test #1

Test #2

Arguments

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

Expected Output

3