用php实现简单的bfs算法,最常见的就是迷宫问题。
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
其中1表示墙,0表示可以走,起点为(0,0),终点为(4,4)
创建一个节点类Node.php
<?php
class Node{
private $x;
private $y;
function __construct($x,$y)
{
$this->x = $x;
$this->y = $y;
}
public function get_x(){
return $this->x;
}
public function get_y(){
return $this->y;
}
}
创建一个BFS类,BFS.php
<?php
/**
* Created by PhpStorm.
* User: 益
* Date: 2018/5/13
* Time: 13:55
*/
class BFS
{
private $map; //图
private $Vs; //起点
private $Vd; //终点
private $len; //图的宽
private $high; //图的高
private $visit; //遍历数组,表示遍历过的地方
public function __construct(&$map,Node &$Vs,Node &$Vd)
{
$this->map = $map;
$this->Vd = $Vd;
$this->Vs = $Vs;
for ($i=0;isset($this->map[$i]);$i++){
$this->high = $i+1;
}
for ($i=0;isset($this->map[0][$i]);$i++){
$this->len = $i+1;
}
}
/**
* @param Node $V 需要判断的节点
* @return bool 如果节点合法返回true,不合法返回false,越界或者为墙表示不合法
*/
private function isValid(Node $V){
if ($V->get_x()<0 || $V->get_x()>$this->len-1 || $V->get_y()<0 || $V->get_y()>$this->high-1){
return false;
}else{
if ($this->map[$V->get_x()][$V->get_y()] != 1) {
return true;
}else{
return false;
}
}
}
/**
* 输出遍历后的数组
*/
public function print_visit(){
for ($i=0;$i<$this->len;$i++){
for ($j=0;$j<$this->high;$j++){
if (isset($this->visit[$i][$j])){
echo "□ ";
}else{
echo "█ ";
}
}
echo "<br>";
}
}
/**
* @return bool 能够走通返回true,不能返回false
*/
public function BFS(){
//声明一个数组$Q作为队列使用
$Q = array();
//定义四个方向
$dir = array(
array(0,1),//right
array(0,-1),//left
array(1,0),//down
array(-1,0)//up
);
//起点入队
array_push($Q,$this->Vs);
//当队列中还有可被遍历的节点时循环
while(count($Q)!=0){
//取出队列第一个元素
$Vn = array_shift($Q);
//该节点被访问,记录在visit数组中
$this->visit[$Vn->get_x()][$Vn->get_y()] = 1;
//四个方向寻找相邻节点
for ($i=0;$i<4;$i++){
//生成一个相邻节点对象
$Vw = new Node($Vn->get_x()+$dir[$i][0],$Vn->get_y()+$dir[$i][1]);
//如果这个相邻的节点是终点,则遍历完成
if ($Vw == $this->Vd){
//获取最短路径,此处省略
$this->visit[$Vw->get_x()][$Vw->get_y()] = 1;
return true;
}
//判断这个相邻节点是否合法,并且这个节点是否被访问过,合法且没有访问过则加入到队列$Q中等待遍历
if($this->isValid($Vw) && !isset($this->visit[$Vw->get_x()][$Vw->get_y()])) {
//合法且未访问过的相邻节点入队
array_push($Q, $Vw);
}
}
}
return false;
}
}
index.php
<?php
/**
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
*/
require_once "Node.php";
require_once "BFS.php";
$maze=array(
array(1,1,1,1,1,1,1,1,1),
array(1,0,0,1,0,0,1,0,1),
array(1,0,0,1,1,0,0,0,1),
array(1,0,1,0,1,1,0,1,1),
array(1,0,0,0,0,1,0,0,1),
array(1,1,0,1,0,1,0,0,1),
array(1,1,0,1,0,1,0,0,1),
array(1,1,0,1,0,0,0,0,1),
array(1,1,1,1,1,1,1,1,1)
);
$maze2=[
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 1, 0],
];
$Vs = new Node(0,0);
$Vd = new Node(4,4);
$bfs = new BFS($maze2,$Vs,$Vd);
//var_dump($bfs);
if ($bfs->BFS()){
echo "有路<br>";
}else{
echo "没有路<br>";
}
$bfs->print_visit();
运行结果