Find SCCs in directed graphs with Golang

Imagine you have to write code to discover groups inside a social network, so then you can suggest them to follow each other or to like some page based on their shared interest.

People in the network can be represented as the vertices of a graph, and the groups as the strongly connected components of it.

strongly connected component (SCC) of a directed graph is the portion of the graph where exists a path between all pairs of vertices. This only works for directed graphs (i.e. where the edges have a direction, they indicate a one-way relationship from one vertex to another).

For example, Figure 1.1 shows a directed graph with four strongly connected components.

Figure 1.1. (Image by author)

The asymptotically best algorithm to find SCCs is Kosaraju’s algorithm, which runs in O(V+E) time.

If you are given a directed graph (G) this algorithm has four steps:

  1. Create an empty stack.
  2. Do depth-first search (DFS) traversal on G, and push each vertex onto the stack.
  3. Create the transpose (GT) of G.
  4. Pop the elements from the stack in a LIFO order until it’s empty. When popping the element call DFS on it. Each call will output an SCC.

#coding #golang #algorithms #go

Go: Strongly Connected Components in Graphs
1.50 GEEK