PHP 利用栈实现迷宫算法

<?php
#迷宫问题
#解决方法
#1.回溯法 从一个节点开始,任意找一个能走的点,当找不到能走的点的时,退回上一个点寻找是否有其他方向的点 使用栈存储当前路径

class Stack{
	private $stack = array();

	#栈是否空
	public function stack_is_null()
	{
		if (count($this->stack) <= 0) {
			return 0;
		} else {
			return 1;
		}
	}
	#进栈
	public function push($value){
		array_push($this->stack,$value);
	}
	#出栈
	public function pop()
	{
		if (!$this->stack_is_null()) {
			return None;
		};
		array_pop($this->stack);

	}
	#取栈顶
	public function get_top()
	{
		if (!$this->stack_is_null()) {
			return None;
		};
		return end($this->stack);
	}
	#返回栈内所有元素
	public function get_stack()
	{
		return $this->stack;
	}
}


$moze = [
	[1,1,1,1,1,1,1,1,1,1],
	[1,0,0,1,0,0,0,1,0,1],
	[1,0,0,1,0,0,0,1,0,1],
	[1,0,0,0,0,1,1,0,0,1],
	[1,0,1,1,1,0,0,0,0,1],
	[1,0,0,0,1,0,0,0,0,1],
	[1,0,1,0,0,0,1,0,0,1],
	[1,0,1,1,1,0,1,1,0,1],
	[1,1,0,0,0,0,0,0,0,1],
	[1,1,1,1,1,1,1,1,1,1],
];

function getDirection($x,$y)
{
	$diretion = [
		[$x-1,$y],
		[$x,$y+1],
		[$x+1,$y],
		[$x,$y-1]
	];
	return $diretion;
}
function moze_path($x,$y,$x1,$y1,$moze)
{
	$stack = new Stack();
	$stack->push([$x,$y]); 							#初始化起点

	while ($stack->stack_is_null()) { 				#如果路径不为空
		$top = $stack->get_top(); 					#获取最新路径
		//var_dump($top);
		if ($top[0] == $x1 && $top[1] == $y1  ) {	#如果路径的点位和终点一样则表示有路
			return $stack->get_stack();				#返回栈内所有的路径
		}
		$diretion = getDirection($top[0],$top[1]);	#获取当前坐标的四个方向
		$i = 0;
		$l = 0;
		while ($i < 4) { 							
			$d = $diretion[$i];						#循环四个方向是否可以走
			if ($moze[$d[0]][$d[1]] == 0 ) {		#如果可以走 就将坐标存入栈
				$stack->push($d);
				//var_dump($stack->get_stack());
				$moze[$d[0]][$d[1]] = 2;			#将走过的路坐标修改为 2
				$l = 1;
				break;
			}
			$i++;
		}
		if (!$l) {
			$moze[$d[0]][$d[1]] = 2; 					#将走过的路坐标修改为 2
			$stack->pop();								#如果四个方向都不能走 则将坐标从栈中移除
		}
	}
	return False;
}

$res = moze_path(1,1,8,8,$moze);
if ($res) {
	echo '有路';
}else{
	echo '没有路';
}








原文地址:https://www.cnblogs.com/ikai/p/11990373.html