Merge pull request #94 from andremralves/master

Add non recursive DFS algorithm
This commit is contained in:
Brandon Johnson 2022-10-31 16:20:05 -06:00 committed by GitHub
commit 9ab57ce999
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 86 additions and 0 deletions

View File

@ -13,6 +13,9 @@
* [Octaltodecimal](./Conversions/OctalToDecimal.php)
* [Speedconversion](./Conversions/SpeedConversion.php)
## Graphs
* [DepthFirstSearch](./Graphs/DepthFirstSearch.php)
## Maths
* [Absolutemax](./Maths/AbsoluteMax.php)
* [Absolutemin](./Maths/AbsoluteMin.php)

View File

@ -0,0 +1,35 @@
<?php
/**
* The Depth-first Search is an algorithm used for traversing or searching trees or graphs
* (https://en.wikipedia.org/wiki/Depth-first_search).
*
* This is a non recursive implementation.
*
* References:
* https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
*
* https://the-algorithms.com/algorithm/depth-first-search?lang=python
*
* @author Andre Alves https://github.com/andremralves
* @param array $adjList An array representing the grapth as an Adjacent List
* @param int|string $start The starting vertex
* @return array The visited vertices
*/
function dfs($adjList, $start)
{
$visited = [];
$stack = [$start];
while (!empty($stack)) {
// Removes the ending element from the stack and mark as visited
$v = array_pop($stack);
$visited[$v] = 1;
// Checks each adjacent vertex of $v and add to the stack if not visited
foreach (array_reverse($adjList[$v]) as $adj) {
if (!array_key_exists($adj, $visited))
array_push($stack, $adj);
}
}
return array_keys($visited);
}

View File

@ -0,0 +1,48 @@
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../Graphs/DepthFirstSearch.php';
use PHPUnit\Framework\TestCase;
class DepthFirstSearchTest extends TestCase
{
public function testDepthFirstSearch()
{
$graph = array(
"A" => ["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);
}
}