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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| <?php class Point { public $x; public $y;
public function __construct($x, $y) { $this->x = $x; $this->y = $y; }
public function __toString() { return "($this->x, $this->y)"; } }
function bfs($map, $start, $end) { $rows = count($map); $cols = count($map[0]); $directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; $queue = new SplQueue(); $queue->enqueue([$start, [$start]]); $visited = [];
while (!$queue->isEmpty()) { list($current, $path) = $queue->dequeue(); $x = $current->x; $y = $current->y;
if ($x == $end->x && $y == $end->y) { return $path; }
foreach ($directions as $direction) { $newX = $x + $direction[0]; $newY = $y + $direction[1]; $newPoint = new Point($newX, $newY);
if ($newX >= 0 && $newX < $rows && $newY >= 0 && $newY < $cols && $map[$newX][$newY] == 0 && !isset($visited["$newX,$newY"])) { $queue->enqueue([$newPoint, array_merge($path, [$newPoint])]); $visited["$newX,$newY"] = true; } } } return null; }
$map = [ [0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0] ];
$start = new Point(0, 0); $end = new Point(4, 4);
$path = bfs($map, $start, $end);
if ($path) { echo "Path found:\n"; foreach ($path as $point) { echo $point . " "; } } else { echo "No path found."; } ?>
|