|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TemplesOfCode\NodesAndEdges\DFS; |
|
4
|
|
|
|
|
5
|
|
|
use TemplesOfCode\NodesAndEdges\Digraph; |
|
6
|
|
|
use TemplesOfCode\NodesAndEdges\Graph; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Class DSCC |
|
10
|
|
|
* |
|
11
|
|
|
* API for Directed Graph Strongly Connected Components |
|
12
|
|
|
* |
|
13
|
|
|
* @package TemplesOfCode\NodesAndEdges\DFS |
|
14
|
|
|
*/ |
|
15
|
|
|
class DSCC extends ConnectedComponent |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* Computes the connected components of the undirected graph g. |
|
19
|
|
|
* |
|
20
|
|
|
* @param Digraph $g the graph |
|
21
|
|
|
*/ |
|
22
|
|
|
public function __construct(Digraph $g) |
|
23
|
|
|
{ |
|
24
|
|
|
// init |
|
25
|
|
|
$this->count = 0; |
|
26
|
|
|
// get vertices |
|
27
|
|
|
$vertices = $g->getVertices(); |
|
28
|
|
|
// set |
|
29
|
|
|
$this->graph = $g; |
|
30
|
|
|
// init |
|
31
|
|
|
$this->marked = array_fill(0, $vertices, false); |
|
32
|
|
|
// init |
|
33
|
|
|
$this->id = array_fill(0, $vertices, null); |
|
34
|
|
|
// build a dfo |
|
35
|
|
|
$dfo = new DepthFirstOrder($g->reverse()); |
|
36
|
|
|
// get the order |
|
37
|
|
|
$reversePostorder = $dfo->reversePostorder(); |
|
38
|
|
|
// iterate over the set |
|
39
|
|
|
foreach ($reversePostorder as $s) { |
|
40
|
|
|
// check if we have touched this vertex |
|
41
|
|
|
if (!$this->marked[$s]) { |
|
42
|
|
|
// run it |
|
43
|
|
|
$this->dfs($s); |
|
44
|
|
|
// increment the count for components |
|
45
|
|
|
$this->count++; |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @param int $v |
|
52
|
|
|
* @param int $w |
|
53
|
|
|
* @return bool |
|
54
|
|
|
*/ |
|
55
|
|
|
public function stronglyConnected(int $v, int $w) |
|
56
|
|
|
{ |
|
57
|
|
|
// delegate to default |
|
58
|
|
|
return $this->connected($v, $w); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Depth-first search for an DirectedGraph |
|
63
|
|
|
* @param int $vertex |
|
64
|
|
|
*/ |
|
65
|
|
|
protected function dfs(int $vertex) |
|
66
|
|
|
{ |
|
67
|
|
|
// we have visited now |
|
68
|
|
|
$this->marked[$vertex] = true; |
|
69
|
|
|
// set the component # |
|
70
|
|
|
$this->id[$vertex] = $this->count; |
|
71
|
|
|
// get the neighbors |
|
72
|
|
|
$neighbors = $this->graph->adjacent($vertex); |
|
73
|
|
|
// iterate over the neighbors |
|
74
|
|
|
foreach ($neighbors as $w) { |
|
75
|
|
|
// check if we have visited |
|
76
|
|
|
if (!$this->marked[$w]) { |
|
77
|
|
|
// lets visit |
|
78
|
|
|
$this->dfs($w); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
} |