C#-Codeusing System;
namespace trainYourProgrammer
{
class MainClass
{
static long PlaceQueens(int n, bool[,] blocked, int line) {
if (line == n)
return 1;
long result = 0;
for (int i = 0; i < n; i++) {
if (blocked [i, line])
continue;
result += PlaceQueens (n, PlaceQueenAt (i, line, n, blocked), line + 1);
}
return result;
}
static long PlaceQueens(int n) {
bool[,] blocked = new bool[n, n];
long result = 0;
for (int i = 0; i < n/2; i++) { //Ausnutzen der Symmetrie
result += 2 * PlaceQueens (n, PlaceQueenAt (i, 0, n, blocked), 1);
}
if (n % 2 == 1)
result += PlaceQueens (n, PlaceQueenAt (n / 2, 0, n, blocked), 1);
return result;
}
static bool[,] PlaceQueenAt(int x, int y, int n, bool[,] blocked) {
int[,] offset = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
bool[,] result = (bool[,]) blocked.Clone();
for(int dir = 0; dir < 8; dir++) {
int x_ = x + offset[dir, 0];
int y_ = y + offset[dir, 1];
while (x_ >= 0 && x_ < n && y_ >= 0 && y_ < n) {
result[x_, y_] = true;
x_ += offset[dir, 0];
y_ += offset[dir, 1];
}
}
return result;
}
static void Main(string[] args) {
for (int i = 8; i < 9; i++) {
Console.WriteLine ("n = " + i.ToString().PadLeft(2) + ": " + PlaceQueens(i).ToString().PadLeft(6) + " Möglichkeiten");
}
}
}
}