Last active
October 17, 2021 01:55
-
-
Save tonysm/8d8d181d6cca90f36b23d5c5d95a14ef to your computer and use it in GitHub Desktop.
8 Queens Puzzle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Queen | |
{ | |
private int $row; | |
public function __construct(private int $column, private ?Queen $neighbour) | |
{ | |
$this->row = 1; | |
} | |
public function findSolution(): bool | |
{ | |
while ($this->neighbour?->canAttack($this->row, $this->column)) { | |
if (! $this->advance()) { | |
return false; | |
} | |
} | |
return true; | |
} | |
private function canAttack(int $row, int $column): bool | |
{ | |
if ($this->row === $row) { | |
return true; | |
} | |
if ($this->canAttackInDiagonal($row, $column)) { | |
return true; | |
} | |
if (! $this->neighbour) { | |
return false; | |
} | |
return $this->neighbour->canAttack($row, $column); | |
} | |
private function canAttackInDiagonal(int $row, int $column): bool | |
{ | |
$columnDiff = $column - $this->column; | |
return $this->row + $columnDiff === $row || $this->row - $columnDiff === $row; | |
} | |
private function advance(): bool | |
{ | |
if ($this->row < 8) { | |
$this->row++; | |
return $this->findSolution(); | |
} | |
if (! $this->neighbour) { | |
return false; | |
} | |
if (! $this->neighbour->advance()) { | |
return false; | |
} | |
if (! $this->neighbour->findSolution()) { | |
return false; | |
} | |
$this->row = 1; | |
return $this->findSolution(); | |
} | |
public function print(): void | |
{ | |
$this->neighbour?->print(); | |
foreach (range(1, 8) as $index) { | |
echo ($index === $this->row | |
? "q" | |
: "."); | |
} | |
echo PHP_EOL; | |
} | |
} | |
$lastQueen = null; | |
for ($i = 1; $i <= 8; $i++) { | |
$lastQueen = new Queen($i, $lastQueen); | |
$lastQueen->findSolution(); | |
} | |
$lastQueen->print(); | |
/** | |
$ php index.php | |
q....... | |
....q... | |
.......q | |
.....q.. | |
..q..... | |
......q. | |
.q...... | |
...q.... | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment