Skip to content

Instantly share code, notes, and snippets.

@Inndy
Created February 20, 2019 18:10
Show Gist options
  • Save Inndy/ab3755807af58cc1655e9f36e3341300 to your computer and use it in GitHub Desktop.
Save Inndy/ab3755807af58cc1655e9f36e3341300 to your computer and use it in GitHub Desktop.
BFS algorithm using PHP
<?php
$maze = '
1111111
1000001
10S1001
1001001
10000E1
1000001
1111111
';
function str2dmap($str) {
$lines = explode("\n", trim($str));
return array_map('str_split', $lines);
}
function find2dmap($map, $v)
{
for($x = 0; $x < count($map); $x++) {
$line = $map[$x];
for($y = 0; $y < count($line); $y++) {
if($line[$y] === $v) {
return [$x, $y];
}
}
}
}
// install php 7.2 and php-ds, or make your own Queue class
function find_path($map, $begin, $end, $QueueClass='\Ds\Queue') {
error_reporting(E_ALL ^ E_NOTICE);
$q = new $QueueClass; // \Ds\Queue or \Ds\Stack
$q->push($begin);
$flag = $map;
$btrace = $map;
list($bx, $by) = $begin;
list($ex, $ey) = $end;
while(!$q->isEmpty()) {
list($x, $y, $prev) = $q->pop();
// visit every point only once
if($flag[$x][$y] === true) continue;
$flag[$x][$y] = true;
// we hit a wall
if($map[$x][$y] === '1') continue;
// record previous point
$btrace[$x][$y] = $prev;
// visit the points around current point
$current = [$x, $y];
$q->push([$x - 1, $y, $current]);
$q->push([$x + 1, $y, $current]);
$q->push([$x, $y - 1, $current]);
$q->push([$x, $y + 1, $current]);
// is it end?
if($x === $ex && $y === $ey) {
// back trace the path
$ret = [$current];
while($prev) {
$ret[] = $prev;
list($x, $y) = $prev;
$prev = $btrace[$x][$y];
}
return array_reverse($ret);
}
}
}
echo $maze;
$map = str2dmap($maze);
$begin = find2dmap($map, 'S');
$end = find2dmap($map, 'E');
printf("Start at (%d, %d)\n", $begin[0], $begin[1]);
printf("End at (%d, %d)\n", $end[0], $end[1]);
$path = find_path($map, $begin, $end);
printf("Path: %s\n", json_encode($path));
[ 02/21 02:09:36 ] inndy @ Fireball ~ (N/A)
$ php bfs.php
1111111
1000001
10S1001
1001001
10000E1
1000001
1111111
Start at (2, 2)
End at (4, 5)
Path: [[2,2],[3,2],[4,2],[4,3],[4,4],[4,5]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment