<?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."; } ?>
|