PHP 解迷宮之 H 最小

jcc123發表於2019-08-03

A*搜尋演算法。目前只保證了H是最小,所以F有可能不是最短的。 F = G + H 。G = 從起點 A 移動到指定方格的移動代價,H = 從指定的方格移動到終點 的估算成本。
體驗地址
原理
1 定義起始點周圍點
2 起始點周圍點距終點距離排序。距離計算方法為 終點座標與改點座標差的絕對值的和
3 選取最近的一個點作為下一點。其它點放進一個陣列中待用(當最近的那個點不能走出的時候,回退使用待用點)
4 不斷重複1,2,3.直到走出終點

PHP 解迷宮之H最小

程式碼

<?php

$n=20;
$positions=[];
for ($i=0;$i<=$n;$i++){
    for ($j=0;$j<=$n;$j++){
        $positions[] =[$j,$i] ;
    }
}

//開始的點
$startDot=[0,0];
//已經放置的點
$placedDot=[];
//不可放置的點
$notPlacedDot=notPlacedDot($positions,$n);
$placedDot[]=$startDot;

//所有穿過的點
list($lineDot,$finishDot)=line($positions,$startDot,$placedDot,$notPlacedDot,$n);

//平面上的所有迷宮點
$mazePositions=mazePosition($positions,$lineDot);

//查詢最小的點
$line=[];
$canReOpen=[];//庫存
$startDot=[0,0];//開始的點
$line[]=[0,0];
$shortLine=getShortLine($line,$canReOpen,$startDot,$mazePositions,$notPlacedDot,$finishDot,$n);
echo "解迷宮";
echo getHtml($positions,$lineDot,$shortLine,$n);
echo "<br>";
echo "迷宮路線";
echo getAllHtml($positions,$lineDot,$n);

function line($positions,$startDot,$placedDot,$notPlacedDot,$n){

    $dotWrapper=GetDotWrappers($startDot);
    $key=rand(0,3);
    $nextDot =  $dotWrapper[$key];

    $i=0;
    $notPlacedDotAll =array_merge($notPlacedDot,[]);
    while (in_array($nextDot,$placedDot)||in_array($nextDot,$notPlacedDotAll)){

        $i++;
       if(badDot($nextDot,$placedDot,$notPlacedDot,$n)){//是否是壞點

           $notPlacedDotAll[]=$nextDot;

          $startDot=$placedDot[count($placedDot)-1];
           $dotWrapper=GetDotWrappers($startDot);
           $key=rand(0,3);
           $nextDot =  $dotWrapper[$key];

          if(badDot($startDot,$placedDot,$notPlacedDotAll,$n)){//本身是否是壞點
              $notPlacedDotAll[]= array_pop($placedDot);

              $startDot=$placedDot[count($placedDot)-1];
              $dotWrapper=GetDotWrappers($startDot);
              $key=rand(0,3);
              $nextDot =  $dotWrapper[$key];

          }

        }else{
            $key=rand(0,3);
            $nextDot =  $dotWrapper[$key];

        }
        if($i>4&&count($placedDot)>1){//迴圈大於3次 還沒找到去除該點
            $i=0;
            $notPlacedDot[]= array_pop($placedDot);
            $startDot=$placedDot[count($placedDot)-1];
            $dotWrapper=GetDotWrappers($startDot);
            $key=rand(0,3);
            $nextDot =  $dotWrapper[$key];

        }

    }

    $placedDot[]=$nextDot;

   if($nextDot[0]>=$n&&$nextDot[1]>0&&$nextDot[1]<=$n){
       return [$placedDot,$nextDot];
   }
   return line($positions,$nextDot,$placedDot,$notPlacedDot,$n);
}

function mazePosition($positions,$lineDot){
    $mazePositions=[];
    foreach ($positions as $position){

            if(in_array($position,$lineDot)){
                $mazePositions[]=$position;
            }
    }
    return $mazePositions;
}

function getShortLine($line,$canReOpen,$startDot,$mazePositions,$notPlacedDot,$endDot,$n){

    if($startDot==$endDot){
//        echo(json_encode($line));
        return $line;
    }

    $dotWrapper=GetDotWrappers($startDot);

    $allOpen = array_reduce($canReOpen, 'array_merge', array());

    $arr=[];

    foreach ($dotWrapper as $dot){

        if(in_array($dot,$mazePositions)&&!in_array($dot,$line)&&!in_array($dot,$allOpen)&&!in_array($dot,$notPlacedDot)){

            $arr[distance($dot,$endDot)][]=$dot;
        }

    }

    if(empty($arr)){//死點
        $notPlacedDot[]=$startDot;//這個點不能放
        array_pop($line);//去除這個點

        $length=count($line);
        $dot=$line[$length-1];//去除上面這個點的最後一個點
        $dotWrapper=GetDotWrappers($dot);//這個點周圍的點

        if(!empty($canReOpen)){//庫存中是否有點
            $reOpen = array_pop($canReOpen);//取出庫存中最後一個庫存
            $ifIntersect=false;
            foreach ($reOpen as $open){
                if(in_array($open,$dotWrapper)){//有交集,說明最後一個庫存可用
                    $ifIntersect=true;
                    break;
                }
            }
            if($ifIntersect){//可用的庫存
                $nextStartDot=array_shift($reOpen);//庫存中的第一個點預設是最短距離的
                array_push($line,$nextStartDot);
                if(!empty($reOpen)){//沒用完,再放進去
                    array_push($canReOpen,$reOpen);
                }
            }else{//不可用。把庫存再放進去
                array_push($canReOpen,$reOpen);
                $nextStartDot = $dot;
            }
        }else{
            $nextStartDot = $dot;
        }
    }else{
        ksort($arr);//按距離大小升序排序

        $arr = array_reduce($arr, 'array_merge', array());
//        echo json_encode($arr);
//        echo "<br>";
        $nextStartDot=array_shift($arr);//取出最小距離的作為開始點

        array_push($line,$nextStartDot);
        if(!empty($arr)){//還有可用的點,放進庫存
            $canReOpen[] = array_values($arr);
        }
    }

    return getShortLine($line,$canReOpen,$nextStartDot,$mazePositions,$notPlacedDot,$endDot,$n);

}

function getAllHtml($positions,$lineDot,$n){
    $str="<table border='1'>";

    foreach (array_chunk($positions,$n+1) as $row){
        $str.="<tr>";
        foreach ($row as $tr){
            if(in_array($tr,$lineDot)){

                $str.="<td style='color: white;background-color: red'>點{$tr[0]},{$tr[1]}</td>";

            }else{
                $str.="<td>{$tr[0]},{$tr[1]}</td>";
            }
        }
        $str.="<tr>";

    };
    $str.="</table>";
    return $str;
}
function getHtml($positions,$lineDot,$shortLine,$n){
    $str="<table border='1'>";

    foreach (array_chunk($positions,$n+1) as $row){
        $str.="<tr>";
        foreach ($row as $tr){
            if(in_array($tr,$lineDot)){
                if(in_array($tr,$shortLine)){
                    $str.="<td style='color: white;background-color: blue'>點{$tr[0]},{$tr[1]}</td>";
                }else{
                    $str.="<td style='color: white;background-color: red'>點{$tr[0]},{$tr[1]}</td>";
                }

            }else{
                $str.="<td>{$tr[0]},{$tr[1]}</td>";
            }
        }
        $str.="<tr>";

    };
    $str.="</table>";
    return $str;
}

function distance($start,$end){
    return abs($end[0]-$start[0])+abs($end[1]-$start[1]);
}

function notPlacedDot($positions,$n)
{

    $notPlacedDot=[];
    foreach ($positions as $position){
        $dotWrapper=GetDotWrappers($position);

        foreach ($dotWrapper as $dot){
            if($dot[0]<0||$dot[1]<0||$dot[0]>$n||$dot[1]>$n){
                $notPlacedDot[]=$dot;
            }
        }
    }
    return $notPlacedDot;
}

/**
 * 是否是壞點
 * @param $dotWrapper
 * @param $placedDot
 * @param $notPlacedDot
 * @return bool
 */
function badDot($position,$placedDot,$notPlacedDot,$n){

    $dotWrapper=GetDotWrappers($position);
    $i=0;
    foreach ($dotWrapper as $dot){
        if($dot[0]<0||$dot[1]<0||$dot[1]>$n||in_array($dot,$placedDot)||in_array($dot,$notPlacedDot)){
            $i++;
        }
    }
    if($i==4){
        return true;
    }
    return false;

}

function GetDotWrappers($placementEd){
    $top = calculateXY($placementEd[0],$placementEd[1],'top');
    $bottom = calculateXY($placementEd[0],$placementEd[1],'bottom');
    $left = calculateXY($placementEd[0],$placementEd[1],'left');
    $right = calculateXY($placementEd[0],$placementEd[1],'right');
    return [$top,$bottom,$left,$right];
}

function calculateXY($x,$y,$default='top')
{
    switch ($default){
        case 'top':
            $y=$y+1;
            break;
        case 'bottom':
            $y=$y-1;
            break;
        case 'left':
            $x=$x-1;
            break;
        case 'right':
            $x=($x+1);
            break;
        case 'left_top':
            $x=($x-1);
            $y=($y+1);
            break;
        case 'right_top':
            $x=($x+1);
            $y=($y+1);
            break;
        case 'right_bottom':
            $x=($x+1);
            $y=($y-1);
            break;
        case 'left_bottom':
            $x=($x-1);
            $y=($y-1);
            break;
    }

    return [$x,$y];
}

NOT IS BECAUSE I WANT TO WRITE,
BUT I WANT TO INCREASE,
SO I GO TO WRITE~~

相關文章