今天在网上看到一个解八皇后问题的解,看不懂原理
#include "stdafx.h" bool f(int Q[8], int dep)
{
for (int i = 0; i < dep; i++)
if ((Q[i] == Q[dep]) ||
(Q[i] - i == Q[dep] - dep) ||
(Q[i] + i == Q[dep] + dep))
return false;
return true;
}
void p(int Q[8])
{
for (int i = 0; i < 8; i++)
printf("%d\n", Q[i]);
}
int _tmain(int argc, _TCHAR* argv[])
{
int nCnt = 0;
int Q[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
int dep;
dep = 0;
while (dep > -1)
{
while (Q[dep] < 8)
{
if (f(Q, dep))
{
if (7 == dep)
{
nCnt ++;
printf("count:%d\n", nCnt);
p(Q);
}
else
break;
}
Q[dep] ++;
}
if ((Q[dep] > 7))
{
Q[dep] = 0;
dep --;
if (dep >= 0)
Q[dep] ++;
}
else
dep ++;
}
char c;
scanf(&c);
return 0;
}