Kosaraju

From Rosetta Code
Revision as of 18:10, 5 February 2017 by rosettacode>Mikymaione (Kosaraju's strongly connected components algorithm)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Kosaraju
You are encouraged to solve this task according to the task description, using any language you may know.
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.

References

C#

<lang csharp>using System; using System.Collections.Generic;

class Node { public enum Colors { Black, White, Gray }

public Colors color { get; set; } public int N { get; }

public Node(int n) { N = n; color = Colors.White; } }

class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; }

/// <summary> /// Kosaraju's strongly connected components algorithm /// </summary> public void Kosaraju() { var L = new HashSet<Node>();

Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray;

foreach (var v in Adj[u]) Visit(v);

L.Add(u); } };

Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: ");

Console.Write(u.N + " "); u.color = Node.Colors.Black;

foreach (var v in Adj[u]) Assign(v, root);

if (u == root) Console.WriteLine(); } };

foreach (var u in V) Visit(u);

foreach (var u in L) Assign(u, u); } }</lang>