DepthFirstOrder::reversePostorder()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace TemplesOfCode\NodesAndEdges\DFS;
5
6
use TemplesOfCode\NodesAndEdges\Graph;
7
8
/**
9
 * Class DepthFirstOrder
10
 * @package TemplesOfCode\NodesAndEdges
11
 */
12
class DepthFirstOrder
13
{
14
    /**
15
     * @var bool[]
16
     */
17
    protected $marked;
18
19
    /**
20
     * @var Graph
21
     */
22
    protected $graph;
23
24
    /**
25
     * @var array
26
     */
27
    private $pre;
28
29
    /**
30
     * @var array
31
     */
32
    private $post;
33
34
    /**
35
     * @var array
36
     */
37
    private $reversePost;
38
39
    /**
40
     * DepthFirstOrder constructor.
41
     *
42
     * @param Graph $graph
43
     */
44
    public function __construct(Graph $graph)
45
    {
46
        // init
47
        $this->pre = [];
48
        // init
49
        $this->post = [];
50
        // init
51
        $this->reversePost = [];
52
        // set
53
        $this->graph = $graph;
54
        // set
55
        $vertices = $graph->getVertices();
56
        // set
57
        $this->marked = array_fill(0, $vertices, false);
58
        // iterate over the vertices
59
        for ($vertex = 0; $vertex < $vertices; $vertex++) {
60
            // check for visit
61
            if (!$this->marked[$vertex]) {
62
                // execute DFS logic
63
                $this->dfs($vertex);
64
            }
65
        }
66
    }
67
68
    /**
69
     * @param int $vertex
70
     */
71
    protected function dfs(int $vertex)
72
    {
73
        // enqueue $vertex - add to end
74
        array_push($this->pre, $vertex);
75
        // mark the visit
76
        $this->marked[$vertex] = true;
77
        // get neighbors
78
        $neighbors = $this->graph->adjacent($vertex);
79
        // iterate over the set
80
        foreach ($neighbors as $w) {
81
            // check for previous visit
82
            if (!$this->marked[$w]) {
83
                // has not been visited yet
84
                $this->dfs($w);
85
            }
86
        }
87
        // enqueue $vertex - add to end
88
        array_push($this->post, $vertex);
89
        // push to the reverse post stack - add to beginning
90
        array_unshift($this->reversePost, $vertex);
91
    }
92
93
    /**
94
     * @return array
95
     */
96
    public function preorder()
97
    {
98
        return $this->pre;
99
    }
100
101
    /**
102
     * @return array
103
     */
104
    public function postorder()
105
    {
106
        return $this->post;
107
    }
108
109
    /**
110
     * @return array
111
     */
112
    public function reversePostorder()
113
    {
114
       return $this->reversePost;
115
    }
116
}