ai寻路广度优先算法-php版本

<?php

// 定义坐标结构
class Coordinate {
    public $x;
    public $y;

    public function __construct($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }
}

// 定义地图大小
define("ROWS", 4);
define("COLS", 4);

// 定义地图数组
$grid = [
    [0, 1, 1, 0],
    [0, 1, 0, 0],
    [0, 0, 0, 0],
    [0, 1, 1, 0]
];

// 定义个移动方向(上、下、左、右)
$direction = [
    new Coordinate(-1, 0), // 上
	new Coordinate(1, 0),  // 下
 new Coordinate(0, -1), // 左
    new Coordinate(0, 1)   // 右
];

// 广度优先搜索算法
function BFS($start, $target, $grid) {
	global $direction;
    // 已经走过的
    $visited = array_fill(0, ROWS, array_fill(0, COLS, false));

    // 定义路线
    $queue = [[$start]];

    // 起点定义已经过
    $visited[$start->x][$start->y] = true;

    while (!empty($queue)) {
        $path = $queue[0];
        $queue = array_slice($queue, 1);

        $node = $path[count($path)-1];
        if ($node->x == $target->x && $node->y == $target->y) {
            return $path;
        }

        foreach ($direction as $dir) {
            $newX = $node->x + $dir->x;
            $newY = $node->y + $dir->y;

            // 检查移动是否越界
 if ($newX < 0 || $newX >= ROWS || $newY < 0 || $newY >= COLS) {
                continue;
            }

            // 检查移动是否遇到障碍物或已访问过的位置
            if ($grid[$newX][$newY] == 1 || $visited[$newX][$newY]) {
                continue;
            }

            // 将新的位置加入路径中
            $newPath = $path;
            $newPath[] = new Coordinate($newX, $newY);
            $queue[] = $newPath;
            $visited[$newX][$newY] = true;
        }
    }

    return null;
}

$start = new Coordinate(0, 0);
$target = new Coordinate(2, 1);

$path = BFS($start, $target, $grid);
if ($path !== null) {
    echo "从起({$start->x},{$start->y})到终点({$target->x},{$target->y})的最短路径为:\n";
    foreach ($path as $node) {
        echo "($node->x, $node->y) ";
    }
    echo "\n";
} else {
    echo "无法从起点({$start->x},{$start->y})到达终点({$target->x},{$target->y})!\n";
}

	?>
posted @ 2023-10-21 15:17  朝阳1  阅读(8)  评论(0编辑  收藏  举报