因解答数的结点无法继续扩展,递归函数不再调用自身,而是返回上一层调用,这种现象我们成为回溯。
在8*8的格子中放置八个皇后,皇后在同一行或同一列或同一对角线上的时候会相互相互攻击,求怎眼放置皇后使得她们不相互攻击。
/*八皇后问题、回溯法,递归枚举 */
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 8
int C[8] = {0};
int tot = 0;
void search(int cur)
{
int i, j;
if(cur == MAXSIZE)
{
tot++;//获得一个放置的方案
for(i = 0; i < 8; i++)
printf("%d ",C[i]);
printf("\n");
}
else
{
for(i = 0; i < MAXSIZE; i++)//每一列尝试
{
int ok = 1;
C[cur] = i;
for(j = 0; j < cur; j++)//是否冲突
{
if(C[j] == C[cur] || cur - C[cur] == j - C[j] || cur + C[cur] == j + C[j])
{
ok = 0;
break;
}
}
if(ok) search(cur + 1);
}
}
}
int main()
{
search(0);
printf("tot = %d",tot);
}