DepthFirstSearch::count()   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
namespace TemplesOfCode\NodesAndEdges\DFS;
4
5
use InvalidArgumentException;
6
use TemplesOfCode\NodesAndEdges\Graph;
7
8
/**
9
 * Class DepthFirstSearch
10
 * @package TemplesOfCode\NodesAndEdges\DFS
11
 */
12
class DepthFirstSearch
13
{
14
    /**
15
     * @var bool[]
16
     */
17
    protected $marked;
18
19
    /**
20
     * @var Graph
21
     */
22
    protected $graph;
23
24
    /**
25
     * @var int
26
     */
27
    private $count;
28
29
    /**
30
     * DepthFirstSearch constructor.
31
     * @param Graph $graph
32
     * @param int $sourceVertex
33
     */
34
    public function __construct(Graph $graph, int $sourceVertex)
35
    {
36
        // validate this vertex in the context of the given graph
37
        Graph::validateVertex($sourceVertex, $graph->getVertices());
38
        // set
39
        $this->graph = $graph;
40
        // set
41
        $this->marked = array_fill(0, $graph->getVertices(), false);
42
        // execute DFS logic
43
        $this->dfs($sourceVertex);
44
    }
45
46
    /**
47
     * Is there a path between the source vertex and vertex v
48
     *
49
     * @param int $vertex
50
     * @return bool true if there is a path, false otherwise
51
     * @throws InvalidArgumentException unless 0 <= $vertex < $vertices
52
     */
53
    public function marked(int $vertex) {
54
        // convenience var
55
        $vertices = $this->graph->getVertices();
56
        // validate this vertex in the context of the given graph
57
        Graph::validateVertex($vertex, $vertices);
58
        // return the flag
59
        return $this->marked[$vertex];
60
    }
61
62
    /**
63
     * @param int $vertex
64
     */
65
    protected function dfs(int $vertex)
66
    {
67
        // bump up
68
        $this->count++;
69
        // mark the visit
70
        $this->marked[$vertex] = true;
71
        // get neighbors
72
        $neighbors = $this->graph->adjacent($vertex);
73
        // iterate over the set
74
        foreach ($neighbors as $w) {
75
            // check for previous visit
76
            if (!$this->marked[$w]) {
77
                // has not been visited yet
78
                $this->dfs($w);
79
            }
80
        }
81
    }
82
83
    /**
84
     * Returns the number of vertices connected to $sourceVertex
85
     *
86
     * @return int  the number of vertices connected to $sourceVertex
87
     */
88
    public function count()
89
    {
90
        return $this->count;
91
    }
92
}
93