forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBreadthFirstSearch.php
37 lines (35 loc) · 1.11 KB
/
BreadthFirstSearch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
/**
* Breadth-first search (BFS) is an algorithm for searching a tree data structure for a node that satisfies a given property.
* (https://en.wikipedia.org/wiki/Breadth-first_search).
*
* This is a non recursive implementation.
*
* References:
* https://cp-algorithms.com/graph/breadth-first-search.html
*
* https://the-algorithms.com/algorithm/depth-first-search?lang=python
*
* @author Aryansh Bhargavan https://github.com/aryanshb
* @param array $adjList An array representing the grapth as an Adjacent List
* @param int|string $start The starting vertex
* @return bool if path between start and end vertex exists
*/
function bfs($adjList, $start, $end, $yes = false){
$visited = [];
$queue = [$start];
while (!empty($queue)) {
$v = array_shift($queue);
$visited[$v] = 1;
foreach ($adjList[$v] as $adj) {
if (!array_key_exists($adj, $visited)) {
array_push($queue, $adj);
}
}
}
// return array_key_exists($end, $visited);
if (array_key_exists($end, $visited)) {
$yes = true;
}
return $yes;
}