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 71 72 73 74 75 76
| <?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 findShortestPath($map, $start, $end, $rewards) { $rows = count($map); $cols = count($map[0]); $directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
$queue = new SplPriorityQueue(); $queue->insert([$start, [$start], 0], 0); $visited = [];
while (!$queue->isEmpty()) { list($current, $path, $cost) = $queue->extract(); $x = $current->x; $y = $current->y;
if ($x == $end->x && $y == $end->y && empty($rewards)) { 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] != 1 && !isset($visited["$newX,$newY"])) { $newCost = $cost + 1; $newRewards = array_filter($rewards, function($reward) use ($newPoint) { return !($reward->x == $newPoint->x && $reward->y == $newPoint->y); });
$queue->insert([$newPoint, array_merge($path, [$newPoint]), $newCost], -$newCost); $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); $rewards = [new Point(2, 2), new Point(3, 1)];
$path = findShortestPath($map, $start, $end, $rewards);
if ($path) { echo "Path found:\n"; foreach ($path as $point) { echo $point . " "; } } else { echo "No path found."; } ?>
|