Kosaraju: Difference between revisions

From Rosetta Code
Content added Content deleted
(Kosaraju's strongly connected components algorithm)
 
m (change to draft status)
Line 1: Line 1:
{{task}}
{{draft task}}
{{wikipedia|Graph}}
{{wikipedia|Graph}}
[[Category:Algorithm]]
[[Category:Algorithm]]

Revision as of 18:57, 5 February 2017

Kosaraju is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
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>