我正在使用 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];
}
}
}