Friday, May 7, 2010

Eight Queen Problem in CSharp

I came across this problem long time back but never had the time and willingness to solve the problem. I sat and solved the problem through nonsense way but not great. This problem can be solved through recursion. I used 8 loops to solve this problem not pretty but OK. program below would give you 92 ways of placing the queens in the board. Open a form and place a listbox as listbox1. solving through recursion is efficient than running 8 loops.

public partial class Form1 : Form
{
int[] columnForRow = { -1, -1, -1, -1, -1, -1, -1, -1 };
private Boolean check(int row)
{
for (int a = 0; a < row; a++)
{
int diff = Math.Abs(columnForRow[a] - columnForRow[row]);
if (diff == 0 || diff == row - a) return false;
}
return true;
}
private void placeeightqueens()
{
for (int i = 0; i <= 7; i++)
{
for (int j = 0; j <= 7; j++)
{
for (int k = 0; k <= 7; k++)
{
for (int l = 0; l <= 7; l++)
{
for (int m = 0; m <= 7; m++)
{
for (int n = 0; n <= 7; n++)
{
for (int o = 0; o <= 7; o++)
{
for (int p = 0; p <= 7; p++)
{
Boolean found = true;

int[] columnForRow_1 = { -1, -1, -1, -1, -1, -1, -1, -1 };

columnForRow_1[0] = i; columnForRow_1[1] = j; columnForRow_1[2] = k; columnForRow_1[3] = l;
columnForRow_1[4] = m; columnForRow_1[5] = n; columnForRow_1[6] = o; columnForRow_1[7] = p;

for (int z = 0; z <= 7; z++)
{
columnForRow[z] = columnForRow_1[z];
if (!check(z)) { found = false; }
}
String S = "";

/*placed 8 queens.*/
if (found)
{
for (int b = 0; b <= 7; b++)
{ S = S + " " + columnForRow[b].ToString(); }
listBox1.Items.Add(S);
}

}
}
}
}
}
}
}
}
MessageBox.Show(listBox1.Items.Count.ToString());
}


}