-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.php
More file actions
41 lines (35 loc) · 1.02 KB
/
Copy pathbfs.php
File metadata and controls
41 lines (35 loc) · 1.02 KB
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
38
39
40
41
<?php
$graph = [
'A' => ['B', 'C'],
'B' => ['A', 'D'],
'D' => ['B'],
'C' => ['A',],
];
//bfs($graph, 'A', 'D'); // true
//bfs($graph, 'A', 'G'); // false
print_r(bfs_path($graph, 'A', 'D')); // ['A', 'B', 'D']
function bfs_path($graph, $start, $end) {
$queue = new SplQueue();
# Enqueue the path
$queue->enqueue([$start]);
$visited = [$start];
while ($queue->count() > 0) {
$path = $queue->dequeue();
# Get the last node on the path
# so we can check if we're at the end
$node = $path[sizeof($path) - 1];
if ($node === $end) {
return $path;
}
foreach ($graph[$node] as $neighbour) {
if (!in_array($neighbour, $visited)) {
$visited[] = $neighbour;
# Build new path appending the neighbour then and enqueue it
$new_path = $path;
$new_path[] = $neighbour;
$queue->enqueue($new_path);
}
};
}
return false;
}