How to resolve the algorithm Kosaraju step by step in the jq programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Kosaraju step by step in the jq programming language
Table of Contents
Problem Statement
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: And report the kosaraju strongly connected component for each node.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Kosaraju step by step in the jq programming language
Source code in the jq programming language
# Fill an array of the specified length with the input value
def dimension($n): . as $in | [range(0;$n) | $in];
# $graph should be an adjacency-list graph with IO==0
def korasaju($graph):
($graph|length) as $length
| def init: {
vis: (false | dimension($length)), # visited
L: [], # for an array of $length integers
t: ([]|dimension($length)), # transposed graph
x: $length # index
};
# input: {vis, L, t, x, t}
def visit($u):
if .vis[$u] | not
then .vis[$u] = true
| reduce ($graph[$u][]) as $v (.;
visit($v)
| .t[$v] += [$u] )
| .x -= 1
| .L[.x] = $u
else .
end ;
# input: {vis, t, c}
def assign($u; $root):
if .vis[$u]
then .vis[$u] = false
| .c[$u] = $root
| reduce .t[$u][] as $v (.; assign($v; $root))
else .
end ;
# For each vertex u of the graph, mark u as unvisited.
init
# For each vertex u of the graph do visit(u)
| reduce range(0;$length) as $u (.; visit($u))
| .c = (null|dimension($length))
# For each element u of L in order, do assign(u, u)
| reduce .L[] as $u (.; assign($u; $u) )
| .c ;
# An example adjacency list using IO==1
def g: [
[1],
[2],
[0],
[1, 2, 4],
[3, 5],
[2, 6],
[5],
[4, 6, 7]
];
korasaju(g)
[0,0,0,3,3,5,5,7]
You may also check:How to resolve the algorithm Copy a string step by step in the AWK programming language
You may also check:How to resolve the algorithm Show ASCII table step by step in the REXX programming language
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Gambas programming language
You may also check:How to resolve the algorithm Sparkline in unicode step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Binary strings step by step in the Yabasic programming language