<?php
function findRoad($arr){
$position = new Position($arr);
$road = new Road($position);
while ($road->next() != [9,9]){
if($road->road->isEmpty()){
return false;
}
}
printMap($road->position->map);
return true;
}
function printMap($map){
$str = '';
foreach ($map as $key => $value){
foreach ($value as $key2 => $item){
if($key2 == 9){
$str .= $item.PHP_EOL;
break;
}
$str .= $item." ";
}
}
echo $str;
}
class Position{
public $position;
public $map;
public function __construct($map)
{
$this->map = $map;
$this->position = [0,0];
}
public function isValid(){
if ($this->map[$this->position[0]][$this->position[1]] == 0 || $this->map[$this->position[0]][$this->position[1]] == '*'){
return false;
}
return true;
}
public function current(){
return $this->position;
}
public function up(){
if($this->position[0] == 0){
return false;
}
$this->position[0] -= 1;
if($this->isValid()){
return true;
}else{
$this->position[0] += 1;
return false;
}
}
public function down(){
if($this->position[0] == 9){
return false;
}
$this->position[0] += 1;
if($this->isValid()){
return true;
}else{
$this->position[0] -= 1;
return false;
}
}
public function left(){
if($this->position[1] == 0){
return false;
}
$this->position[1] -= 1;
if($this->isValid()){
return true;
}else{
$this->position[1] += 1;
return false;
}
}
public function right(){
if($this->position[1] == 9){
return false;
}
$this->position[1] += 1;
if($this->isValid()){
return true;
}else{
$this->position[1] -= 1;
return false;
}
}
public function setZero(){
$this->map[$this->position[0]][$this->position[1]] = 0;
}
public function setStar(){
$this->map[$this->position[0]][$this->position[1]] = '*';
}
}
class Road{
public $road;
public $position;
public $direction;
public function __construct(Position $position)
{
$this->road = new SplStack();
$this->position = $position;
$this->direction = [
'up','down','left','right'
];
}
public function next(){
if($this->road->isEmpty()){
$this->road->push($this->position->position);
$this->position->setStar();
}
$canNext = false;
foreach ($this->direction as $value){
$res = $this->position->$value();
if($res == true){
$canNext = true;
$this->road->push($this->position->position);
$this->position->setStar();
break;
}
}
if(!$canNext){
$this->position->setStar();
$this->back();
}
return $this->position->position;
}
public function back(){
$this->road->pop();
if($this->road->isEmpty()){
$this->position->position = [0,0];
}else{
$this->position->position = $this->road->top();
}
}
}
$arr = [
[1,0,1,1,1,0,1,1,1,0],
[1,0,1,0,1,0,1,0,1,0],
[1,0,1,0,1,0,1,0,1,0],
[1,0,1,0,1,0,1,0,1,0],
[1,0,1,0,1,0,1,0,1,0],
[1,0,1,0,1,0,1,0,1,0],
[1,0,1,0,1,0,1,0,1,0],
[1,0,1,0,1,0,1,0,1,0],
[1,0,1,0,1,0,1,0,1,0],
[1,1,1,0,1,1,1,1,1,1],
];
findRoad($arr);