Eight queens puzzle C#
using System;
namespace _8ferz
{
public class Program
{
public int[,] board = new int[8, 8];
public void resetQ(int i, int j)
{
for (int x = 0; x < 8; ++x)
{
--board[x, j];
--board[i, x];
int k;
k = j - i + x;
if (k >= 0 && k < 8)
--board[x, k];
k = j + i - x;
if (k >= 0 && k < 8)
--board[x, k];
}
board[i, j] = 0;
}
public bool tryQ(int i)
{
bool result = false;
for (int j = 0; j < 8; ++j)
{
if (board[i, j] == 0)
{
setQ(i, j);
if (i == 7)
result = true;
else
{
if (!(result = tryQ(i + 1)))
resetQ(i, j);
}
}
if (result)
break;
}
return result;
}
public void setQ(int i, int j)
{
for (int x = 0; x < 8; ++x)
{
++board[x, j];
++board[i, x];
int k;
k = j - i + x;
if (k >= 0 && k < 8)
++board[x, k];
k = j + i - x;
if (k >= 0 && k < 8)
++board[x, k];
}
board[i, j] = -1;
}
public static void Main(string[] args)
{
Program p=new Program();
for (int i = 0; i < 8; ++i)
for (int j = 0; j < 8; ++j)
p.board[i, j] = 0;
p.tryQ(0);
for (int i = 0; i < 8; ++i)
{
for (int j = 0; j < 8; ++j)
{
if (p.board[i, j] == -1)
Console.Write("[]");
else
Console.Write( ". ");
}
Console.Write("\n");
}
Console.ReadKey();
}
}
}