How to resolve the algorithm Kosaraju step by step in the Perl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Kosaraju step by step in the Perl 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 Perl programming language
Source code in the perl programming language
use strict;
use warnings;
use feature 'say';
sub kosaraju {
our(%k) = @_;
our %g = ();
our %h;
my $i = 0;
$g{$_} = $i++ for sort keys %k;
$h{$g{$_}} = $_ for keys %g; # invert
our(%visited, @stack, @transpose, @connected);
sub visit {
my($u) = @_;
unless ($visited{$u}) {
$visited{$u} = 1;
for my $v (@{$k{$u}}) {
visit($v);
push @{$transpose[$g{$v}]}, $u;
}
push @stack, $u;
}
}
sub assign {
my($u, $root) = @_;
if ($visited{$u}) {
$visited{$u} = 0;
$connected[$g{$u}] = $root;
assign($_, $root) for @{$transpose[$g{$u}]};
}
}
visit($_) for sort keys %g;
assign($_, $_) for reverse @stack;
my %groups;
for my $i (0..$#connected) {
my $id = $g{$connected[$i]};
push @{$groups{$id}}, $h{$i};
}
say join ' ', @{$groups{$_}} for sort keys %groups;
}
my %test1 = (
0 => [1],
1 => [2],
2 => [0],
3 => [1, 2, 4],
4 => [3, 5],
5 => [2, 6],
6 => [5],
7 => [4, 6, 7]
);
my %test2 = (
'Andy' => ['Bart'],
'Bart' => ['Carl'],
'Carl' => ['Andy'],
'Dave' => [<Bart Carl Earl>],
'Earl' => [<Dave Fred>],
'Fred' => [<Carl Gary>],
'Gary' => ['Fred'],
'Hank' => [<Earl Gary Hank>]
);
kosaraju(%test1);
say '';
kosaraju(%test2);
You may also check:How to resolve the algorithm User input/Graphical step by step in the BaCon programming language
You may also check:How to resolve the algorithm Empty program step by step in the Io programming language
You may also check:How to resolve the algorithm Multifactorial step by step in the Nim programming language
You may also check:How to resolve the algorithm Monty Hall problem step by step in the AWK programming language
You may also check:How to resolve the algorithm Statistics/Basic step by step in the zkl programming language