簡體   English   中英

使用廣度優先搜索用PHP解決3x3難題

[英]Solving 3x3 puzzle with PHP using Breadth-first search

我正在使用PHP制作3x3解謎器。 零是您可以移動的自由空間。 例如:

1 2 3  
4 0 5  
7 8 6   

1 2 3  
4 5 0  
7 8 6   

1 2 3  
4 5 6  
7 8 0   

我已經制作了隨機發生器-進行了50次隨機移動。 但是我與求解器算法堆疊在一起。

輸出應該是解決它的所有步驟。

我已經有了解決單步難題的工作方法,但是我不知道如何遞歸使用它。

public function makeMoves($elements)
{
    $pos = $this->findSpace($elements); //returns position of the free space

    $actions = $this->findActions($pos); //returns all actions positions (left, right, top, bottom)

    $possibleActions = $this->findPossibleActions($actions); //return number of possible actions

    for ($i = 1; $i <= $possibleActions; ++$i) { //let's do all possible actions
        $move = $this->selectAction($actions, $i, $pos); //get new position for the space
        $perform = $this->performAction($elements, $pos, $move); //swap the space with the element on that position

        $this->tree[] = new Elements;

        end($this->tree);
        $last_id = key($this->tree);

        $this->tree[$last_id]->setState($perform);
        $this->tree[$last_id]->setAncestor(0);

        $step = [$move, $pos];

        $this->tree[$last_id]->setStep($step);

        if ($perform == $this->elementsDone) { 
            return $this->tree[$last_id];
        }
    }
}

一種解決方案是使用A *算法找到解決方案的最短路徑。 每次移動的成本為2。每個位置與每個零件必須移動的距離之和的理想解有一個距離。 (一個角到另一個角是距離4。)如果有一個,則可以保證找到最短的解決方案。

有關該算法的實現,請參見http://www.briangrinstead.com/blog/astar-search-algorithm-in-javascript

請注意,所有隨機配置的一半將無法解決。 請參閱https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html進行測試,以告訴您哪些東西要扔掉。 它還為如何編寫一種算法提供了提示,該算法比我建議的算法占用更少的內存,並且發現效率低下的解決方案,但是找到這些解決方案的工作卻更少。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM