前言
回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。
代码(C#)
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int n = 6;
N_Queen(n);
}
public Boolean Place(int[] Column, int index)
{
int i;
for (i = 1; i < index; i++)
{
int Colunm_differ = System.Math.Abs(Column[index] - Column[i]);
int Row_differ = System.Math.Abs(index - i);
if (Column[i] == Column[index] || Colunm_differ == Row_differ)
{
return false;
}
}
return true;
}
public void N_Queen(int n)
{
int[] Column_Num = new int[n + 1];
int index = 1;
int i;
int answer_num = 0;
for (i = 1; i <= n; i++)
{
Column_Num[i] = 0;
while (index > 0)
{
Column_Num[index]++;
while (Column_Num[index] <= n && !Place(Column_Num, index))
{
Column_Num[index]++;
}
if (Column_Num[index] <= n)
{
if (index == n)
{
answer_num++;
txt1.Text = txt1.Text + "\r\n" + "方案" + answer_num;
for (i = 1; i <= n; i++)
{
txt1.Text = txt1.Text + "(" + i + "," + Column_Num[i] + ")";
}
for (i = 1; i <= n; i++)
{
Column_Num[index]++;
}
}
else
{
index++;
Column_Num[index] = 0;
}
}
else
{
index--;
}
}
}
}