-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn-queens-problem.php
52 lines (43 loc) · 1.24 KB
/
n-queens-problem.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
/**
* @author Rodrigo Tejedor
* n queens problem
* usage: php <file> <number-of-queens>
*/
define('N', $argv[1] ?: 8);
if ($solution = placeQueen(array(), 0, array(), array(), array())) {
printSolution($solution);
} else {
echo "No solution";
}
function placeQueen($positions, $index, $columns, $ascDiagonals, $descDiagonals)
{
if ($index == N) return $positions;
for ($i = 0; $i < N; $i++) {
if ($columns[$i] || $ascDiagonals[$i + $index] || $descDiagonals[N + $i - $index]) {
continue;
}
$positions[$index] = $i;
$columns[$i] = true;
$ascDiagonals[$i + $index] = true;
$descDiagonals[N + $i - $index] = true;
if ($solution = placeQueen($positions, $index + 1, $columns, $ascDiagonals, $descDiagonals)) {
return $solution;
}
$columns[$i] = false;
$ascDiagonals[$i + $index] = false;
$descDiagonals[N + $i - $index] = false;
}
}
function printSolution($positions)
{
foreach ($positions as $position) {
echo sprintf(
"%sQ%s\r\n",
str_repeat('.', $position),
str_repeat('.', N - $position)
);
}
echo "\r\n";
echo "[" . implode(',', $positions) . "]";
}