diff --git a/DIRECTORY.md b/DIRECTORY.md index 1ac3968..edd3260 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -13,6 +13,9 @@ * [Octaltodecimal](./Conversions/OctalToDecimal.php) * [Speedconversion](./Conversions/SpeedConversion.php) +## Graphs + * [DeothFirstSearch](./Graphs/DepthFirstSearch.php) + ## Maths * [Absolutemax](./Maths/AbsoluteMax.php) * [Absolutemin](./Maths/AbsoluteMin.php) diff --git a/Graphs/DepthFirstSearch.php b/Graphs/DepthFirstSearch.php new file mode 100644 index 0000000..936484c --- /dev/null +++ b/Graphs/DepthFirstSearch.php @@ -0,0 +1,35 @@ + ["B", "C", "D"], + "B" => ["A", "D", "E"], + "C" => ["A", "F"], + "D" => ["B", "D"], + "E" => ["B", "F"], + "F" => ["C", "E", "G"], + "G" => ["F"], + ); + $visited = dfs($graph, "A"); + $this->assertEquals(["A", "B", "D", "E", "F", "C", "G"], $visited); + } + public function testDepthFirstSearch2() + { + $graph = array( + [1, 2], + [2], + [0, 3], + [3], + ); + + $visited = dfs($graph, 2); + $this->assertEquals([2, 0, 1, 3], $visited); + } + public function testDepthFirstSearch3() + { + $graph = array( + [2, 3, 1], + [0], + [0, 4], + [0], + [2], + ); + $visited = dfs($graph, 0); + $this->assertEquals([0, 2, 4, 3, 1], $visited); + } +}