参考:
http://www.cnblogs.com/jillzhang/archive/2007/10/21/922830.html
现在有个疑惑,用这种方法如何打印出所有的可能情况?
#include<stdio.h>
#define Bool int
#define True 1
#define False 0
Bool IsSafe(int col,int row,int queenList[])
{
int tempCol;
int tempRow;
//只检查前面的列
for (tempCol = 0; tempCol < col; tempCol++)
{
tempRow = queenList[tempCol];
if (tempRow == row)
{
//同一行
return False;
}
if (tempCol == col)
{
//同一列
return False;
}
if (tempRow - tempCol == row - col || tempRow + tempCol == row + col)
{
return False;
}
}
return True;
}
Bool PlaceQueue(int queenList[], int col)
{
int row = 0;
Bool foundSafePos = False;
if (col == 8) //结束标志
{
//当处理完第8列的完成
foundSafePos = True;
}
else
{
while (row < 8 && !foundSafePos)
{
if (IsSafe(col, row, queenList))
{
//找到安全位置
queenList[col] = row;
//找下一列的安全位置
foundSafePos = PlaceQueue(queenList, col + 1);
if (!foundSafePos)
{
row++;
}
}
else
{
row++;
}
}
}
return foundSafePos;
}
int main()
{
int i;
int queenList[8];
int j;
for(j=0; j<8 ;j++)
{
queenList[0]=j;
PlaceQueue(queenList,1);
for(i=0; i<8;i++)
printf("%d ",queenList[i]);
printf("\n");
}
}