PHP Source Code
<?php
// eight-queens
// Author: Hannes du Plooy
// Date: 5 June 2016
// Objective: To solve the following
// Search for a chess board solution with 8 queens and no one
// endangering any other.
$board = array(0,0,0,0,0,0,0,0);
function EightQueens($line) {
global $board;
if ($line > 7) {
return true;
}
for($column=0;$column<8;$column++) {
$endangered = false;
for($line2=0;$line2<$line;$line2++) {
if ($board[$line2] == $column || abs($line-$line2) == abs($column-$board[$line2])) {
$endangered = true;
break;
}
}
if (!$endangered) {
$board[$line] = $column;
if (EightQueens($line+1)) {
return true;
}
}
}
return false;
}
if (EightQueens(0)) {
for($i=0;$i<8;$i++) {
for($j=0;$j<8;$j++) {
if ($board[$i] == $j) {
echo "Q";
} else {
echo ".";
}
}
echo "\n";
}
}