

 This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)



Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.


For this task consider the directed graph with these connections:

 0 -> 1
 1 -> 2
 2 -> 0
 3 -> 1,  3 -> 2,  3 -> 4
 4 -> 3,  4 -> 5
 5 -> 2,  5 -> 6
 6 -> 5
 7 -> 4, 7  -> 6, 7 -> 7

And report the kosaraju strongly connected component for each node.



References

 The article on Wikipedia.
type
  Vertex = int
  Graph = seq[seq[Vertex]]
  Scc = seq[Vertex]
 
func korasaju(g: Graph): seq[Scc] =
 
  var
    size = g.len
    visited = newSeq[bool](size)        # All false by default.
    l = newSeq[Vertex](size)            # All zero by default.
    x = size                            # Index for filling "l" in reverse order.
    t = newSeq[seq[Vertex]](size)       # Transposed graph.
    c = newSeq[Vertex](size)            # Used for component assignment.
 
  func visit(u: Vertex) =
    if not visited[u]:
      visited[u] = true
      for v in g[u]:
        visit(v)
        t[v].add(u)   # Construct transposed graph.
      dec x
      l[x] = u
 
  func assign(u, root: Vertex) =
    if visited[u]:
      # Repurpose visited to mean 'unassigned'.
      visited[u] = false
      c[u] = root
      for v in t[u]: v.assign(root)
 
  for u in 0..g.high: u.visit()
  for u in l: u.assign(u)
 
  # Build list of strongly connected components.
  var prev = -1
  for v1, v2 in c:
    if v2 != prev:
      prev = v2
      result.add @[]
    result[^1].add v1
 
 
when isMainModule:
  let g = @[@[1], @[2], @[0], @[1, 2, 4], @[3, 5], @[2, 6], @[5], @[4, 6, 7]]
  for scc in korasaju(g): echo $scc